1、指定key-value,value是对象中的某个属性值。
Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身
Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。
Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
5、将List根据某个属性进行分组,放入Map;然后组装成key-value格式的数据,分组后集合的顺序会被改变,所以事先设置下排序,然后再排序,保证数据顺序不变。
List<GoodsInfoOut> lst = goodsInfoMapper.getGoodsList();
Map<String, List<GoodsInfoOut>> groupMap = lst.stream().collect(Collectors.groupingBy(GoodsInfoOut::getClassificationOperationId));
List<HomeGoodsInfoOut> retList = groupMap.keySet().stream().map(key -> {
HomeGoodsInfoOut mallOut = new HomeGoodsInfoOut();
mallOut.setClassificationOperationId(key);
if(groupMap.get(key)!=null && groupMap.get(key).size()>0) {
mallOut.setClassificationName(groupMap.get(key).get(0).getClassificationName());
mallOut.setClassificationPic(groupMap.get(key).get(0).getClassificationPic());
mallOut.setClassificationSort(groupMap.get(key).get(0).getClassificationSort());
}
mallOut.setGoodsInfoList(groupMap.get(key));
return mallOut;
}).collect(Collectors.toList());
List<HomeGoodsInfoOut> homeGoodsInfoOutList = retList.stream().sorted(Comparator.comparing(HomeGoodsInfoOut::getClassificationSort))
.collect(Collectors.toList());
5、根据用户性别将数据 - 分组
Map<String, List<UserInfo>> groupMap = userList.stream().collect(Collectors.groupingBy(UserInfo::getSex()));
6、List实体转Map,想要有序的话,就使用以下操作(TreeMap 有序;Map 无序)
TreeMap<String, List<BillPollEntity>> ascMonthBillPollMap = s.stream().collect(Collectors.groupingBy(t -> t.getDrawTime()), TreeMap::new, Collectors.toList()));
//倒叙MAP
NavigableMap<String, List<OpenActivityOut>> descMonthBillPollMap = ascMonthBillPollMap.descendingMap();
Map<String, List<BillPollEntity>> monthBillPollMap = s.stream().collect(Collectors.groupingBy(BillPollEntity::getDrawTime));