一、List转Map
集合转Map对象
List nodes = pdataRealtimeMapper.findByNodeIds(nodeIds); Map<String, PdataRealtime> map = nodes.stream().collect(Collectors.toMap(PdataRealtime::getNodeId, Function.identity(), (key1, key2) -> key1));
Collectors.toMap():返回一个Map vale为一个对象 Function.identity():返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t形式的Lambda表达式。 (key1, key2) -> key1):Map对象Key不可重复, (key1, key2) -> key1)若出现重复以第一次出现的数据为准
集合转map List,分组
List deptList1 = new ArrayList<>(); Map<Integer,List> map2 = deptList1.stream().collect(Collectors.groupingBy(SysDept::getParentId)); Collectors.groupingBy(SysDept::getParentId)取对象属性为Key进行分组
集合排序Sort List<对象> list = new ArryList<>() List = list.sort(Comparator.comparing(对像::get对象属性));
Sort方法传递的并非Comparator类型,但结果仍然正确排序,原因就在于我们比较的是String,而String已经实现了Comparable接口,查看Comparator.comparing()的定义实现,我们可以看到其,其实调用的就是比较关键子的comoareTo方法
集合过滤
list = list.stream().filter(userInfo -> userInfo.getAge()==26).collect(Collectors.toList());
stream().filter()方法过滤年龄等于26的数据
集合按条目拆分
//计算切分次数
int limit = countStep(list.size(),maxSend);
List<List<对象>> pList = new ArrayList<>();
Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
pList.add(list.stream().skip(i * maxSend).limit(maxSend).collect(Collectors.toList()));
});
/**
* 计算切分次数
*/
private static Integer countStep(Integer size,int maxSend) {
return (size + maxSend - 1) / maxSend;
}
countStep():计算拆分次数 Stream.iterate():进行拆分