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));   

posted @ 2021-08-20 16:44  了悟  阅读(10586)  评论(0编辑  收藏  举报