| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- 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<Student> list = new ArrayList<>(List.of(s1, s2, s3, s4, s5, s6, s7));
- /*
- public static <T, K, U> Collector<T, ?, Map<K,U>>
- toMap
- (
- Function<? super T, ? extends K> keyMapper,
- Function<? super T, ? extends U> valueMapper
- )
- 贪心思想----局部最优解,不代表全局最优解
- */
- Map<Integer,Student>map=list //集合对象
- .stream()
- .collect(Collectors.toMap(
- student->student.getId()//键
- ,
- student->student //值
- ));
- System.out.println(map);
- Map<Integer,Student>map1=list //集合对象
- .stream()
- .collect(Collectors.toMap(
- new Function<Student, Integer>() {
- @Override
- public Integer apply(Student student) {
- return student.getId();
- }
- }
- ,
- new Function<Student, Student>() {
- @Override
- public Student apply(Student student) {
- return student;
- }
- }
- ));
- }
- }
|