java list转map的几种方式


1.转成一对一的,一个id对应一个对象

Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));   后面的key1,key2 是指定一种覆盖规则,防止key冲突   

2.如果想要得到某一属性而不是 整个对象方法

Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));

3.转成一对多的,一个id对应多个对象

Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));   


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。