ToMapDemo.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package course;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.function.Function;
  6. import java.util.stream.Collectors;
  7. /**
  8. * @author WanJl
  9. * @version 1.0
  10. * @title ToMapDemo
  11. * @description
  12. * @create 2026/8/4
  13. */
  14. public class ToMapDemo {
  15. public static void main(String[] args) {
  16. Student s1 = new Student(1001, "项羽");
  17. Student s2 = new Student(1002, "张良");
  18. Student s3 = new Student(1003, "项庄");
  19. Student s4 = new Student(1004, "刘邦");
  20. Student s5 = new Student(1005, "萧何");
  21. Student s6 = new Student(1006, "韩信");
  22. Student s7 = new Student(1007, "樊哙");
  23. ArrayList<Student> list = new ArrayList<>(List.of(s1, s2, s3, s4, s5, s6, s7));
  24. /*
  25. public static <T, K, U> Collector<T, ?, Map<K,U>>
  26. toMap
  27. (
  28. Function<? super T, ? extends K> keyMapper,
  29. Function<? super T, ? extends U> valueMapper
  30. )
  31. 贪心思想----局部最优解,不代表全局最优解
  32. */
  33. Map<Integer,Student>map=list //集合对象
  34. .stream()
  35. .collect(Collectors.toMap(
  36. student->student.getId()//键
  37. ,
  38. student->student //值
  39. ));
  40. System.out.println(map);
  41. Map<Integer,Student>map1=list //集合对象
  42. .stream()
  43. .collect(Collectors.toMap(
  44. new Function<Student, Integer>() {
  45. @Override
  46. public Integer apply(Student student) {
  47. return student.getId();
  48. }
  49. }
  50. ,
  51. new Function<Student, Student>() {
  52. @Override
  53. public Student apply(Student student) {
  54. return student;
  55. }
  56. }
  57. ));
  58. }
  59. }