1、list去重
//list对象中的属性去重
authUsers = authUsers.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(AuthUser::getLoginName))), ArrayList::new));
//list的属性直接去重
List<String> roleNameList = roleNameList.stream().distinct().collect(Collectors.toList());
2、list过滤
//将结果收集到List中
userRoleNameList = userRoleNameList.stream().filter(r -> StringUtils.isNotEmpty(r.getRoleName())).collect(Collectors.toList());
3、list提取对象属性
List<String> authNameList = nodeRoleLogList.stream().map(ApprovalConfigNodeRoleLog::getAuthName).collect(Collectors.toList());
4、list转map
//转list
Map<String,List<Reviewer>> reviewerMap = reviewerList.stream().collect(Collectors.groupingBy(Reviewer::getRoleName));
//转对象
Map<String, UserSelectResponse> accountMap = reviewersWithRole.stream().collect(Collectors.toMap(UserSelectResponse::getLoginName, Function.identity()));
//转属性与属性
Map<String, String> map = userList.stream().distinct().collect(Collectors.toMap(AuthUser::getLoginName, AuthUser::getEmpName));
//list对象中的属性转map
List<GroupInfo> groupInfoList = nwe new ArrayList<>();
Map<String,List<String>> departmentId_deptIdList_map = groupInfoList.stream().collect(Collectors.groupingBy(GroupInfo::getDepartmentId,Collectors.mapping(GroupInfo::getDeptid,Collectors.toList())));
5、list对象字段排序
//排序
reviewerList = reviewerList.stream().sorted(Comparator.comparing(Reviewer::getSort)).collect(Collectors.toList());
//升序
authMenus.sort(Comparator.comparing(AuthMenu::getSort));
//降序
authMenus.sort(Comparator.comparing(AuthMenu::getSort).reversed());
//下标对调,即:前面的直接到后面,后面的直接到前面
Collections.reverse(belongList);
//多个字段进行排序
sysWorkingList = sysWorkingList.stream().sorted(Comparator.comparing(WorkingApprovalDto::getDepartmentName)
.thenComparing(WorkingApprovalDto.SysWorking::getGroupCode).thenComparing(WorkingApprovalDto::getSysName)).collect(Collectors.toList());
6、将List<String>拼接成字符串
List<String> authNameList = new ArrayList<>();
authNameList.add("1");
authNameList.add("2");
authNameList.add("3");
//将List<String>拼接成字符串,如下
String collect = authNameList.stream().collect(Collectors.joining(","));
System.out.println(collect);
//List<Long> 转成字符串
List<Long> hiddenDangerImgIdList = new ArrayList<>();
String collect = String.join(",", hiddenDangerImgIdList.stream().map(String::valueOf).collect(Collectors.toList()));
//字符串转list
String idStr = "1,2,3";
List<Long> listIds = Arrays.asList(idStr.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
效果如下:
7、list求和
List<Double> filledHoursList = new ArrayList<>();
Double b = filledHoursList.stream().mapToDouble(Double::doubleValue).sum();
List<BigDecimal> collect = new ArrayList<>();
BigDecimal b = collect.stream().reduce(BigDecimal.ZERO, BigDecimal::add);