list转map的三种方法( 三 )



        Student Student2 = new Student();
        Student2.setId(2L);
        Student2.setAge("13");


        Student Student3 = new Student();
        Student3.setId(2L);
        Student3.setAge("14");


        StudentList.add(Student1);
        StudentList.add(Student2);
        StudentList.add(Student3);


        /**
         * List -> Map
         * 需要注重的是:
         * toMap 若是调集对象有反复的key , 会报错Duplicate key ....
         *  apple1,apple12的id都为1 。
         *  可以用 (k1,k2)->k1 来设置 , 若是有反复的key,则保留key1,舍弃key2 或者可以用 (k1,k2)->k2 来设置 , 若是有反复的key,则保留key2,舍弃key1
         */
        Map<Long, String> maps = StudentList.stream().collect(Collectors.toMap(Student::getId,Student::getAge, (v1,v2)->v1));
        System.out.println(maps);
    }
}

list转map的三种方法

文章插图

注重事项jdk1.8
若有更好的体例和弥补请在经验下提出!

以上内容就是list转map的三种方法的内容啦 , 希望对你有所帮助哦!

推荐阅读