package course; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * @author WanJl * @version 1.0 * @title ToMapDemo * @description * @create 2026/8/4 */ public class ToMapDemo { public static void main(String[] args) { Student s1 = new Student(1001, "项羽"); Student s2 = new Student(1002, "张良"); Student s3 = new Student(1003, "项庄"); Student s4 = new Student(1004, "刘邦"); Student s5 = new Student(1005, "萧何"); Student s6 = new Student(1006, "韩信"); Student s7 = new Student(1007, "樊哙"); ArrayList list = new ArrayList<>(List.of(s1, s2, s3, s4, s5, s6, s7)); /* public static Collector> toMap ( Function keyMapper, Function valueMapper ) 贪心思想----局部最优解,不代表全局最优解 */ Mapmap=list //集合对象 .stream() .collect(Collectors.toMap( student->student.getId()//键 , student->student //值 )); System.out.println(map); Mapmap1=list //集合对象 .stream() .collect(Collectors.toMap( new Function() { @Override public Integer apply(Student student) { return student.getId(); } } , new Function() { @Override public Student apply(Student student) { return student; } } )); } }