最近项目使用了一些stream语法,下面取出一部分备忘:
1.将枚举对象的值转为map集合
@Override
public List<Map> getInteractionTypeList() {
return Arrays.stream(InteractionType.values()).map(item -> {
Map map = new HashMap();
map.put("key",item.getKey());
map.put("value",item.getValue());
return map;
}).collect(Collectors.toList());
}
2.concat合并数组
@Override
public List<Integer> getProduceProcessAndChildIdList(ProduceProcessDTO dto) {
List<Integer> list = new ArrayList<>();
if(dto!=null&&dto.getId()!=null){
list.add(dto.getId());
}
for (ProduceProcessDTO item:dto.getChildNodes()) {
if(item!=null&&item.getId()!=null){
list = Stream.concat(list.stream(),getProduceProcessAndChildIdList(item).stream()).collect(Collectors.toList());
}
}
return list;
}
3.过滤list中的对象,再将对象中某个属性按逗号拼接返回字符串
String finishNumber = subPlanCountDTOList.stream().filter((e) -> {
return e.getProcessType().equals(processType.getKey());
}).map(subPlanCountDTO ->
subPlanCountDTO.getSubFinishNumber().toString()).collect(Collectors.joining(","));
4.将list中对象的某个属性取出放到list中
workSheets.stream().map(item->item.getWorkSheetCode()).collect(Collectors.toList());
5.将list中对象的某个属性取出放到list中,然后去重再生成list
workSheets.stream().map(item->item.getSubPlanCode()).collect(Collectors.toList())
.stream().distinct().collect(Collectors.toList());
6.按某个属性值排序 返回list
map.entrySet().stream().map(e->e.getValue()).sorted(Comparator.comparing(LineFinishDTO::getLineId)).collect(Collectors.toList())
//排序 .reversed()反转顺序
list = list.stream().sorted(Comparator.comparing(PlanFinishNumberDTO::getStartDate)).collect(Collectors.toList());