Java-list,map常用操作
简单升序和降序 1 2 3 4 List<Long> refactorReports = List.of(5L , 3L , 9L , 1L , 4L ); Collections.sort(refactorReports, Comparator.naturalOrder());
1 2 3 4 List<Long> refactorReports = List.of(5L , 3L , 9L , 1L , 4L ); Collections.sort(refactorReports, Comparator.reverseOrder());
List分页 1 2 voList=voList.stream().skip((long ) queryDTO.getPageSize() * (queryDTO.getPageNum() - 1 )) .limit(queryDTO.getPageSize()).collect(Collectors.toList());
返回其他类型的集合 1 2 3 4 5 6 7 8 9 public static List<ReportTemplateVO> toReportTemplateVO (List<RefactorReportTemplate> templates, RefactorReportContentTemplateService contentTemplateService, Boolean isCopy) { Map<Long, List<RefactorReportContentTemplate>> contentTemplateMap = contentTemplateService.list().stream().collect(Collectors.groupingBy(RefactorReportContentTemplate::getTemplateBaseId)); return templates.stream() .map(template -> { List<RefactorReportContentTemplate> ct = contentTemplateMap.getOrDefault(template.getTemplateBaseId(), Collections.emptyList()); return toReportTemplateVO(template, ct, isCopy); }).collect(Collectors.toList()); }
List用属性名称变量排序 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 if (queryDTO.getAsc()) {voList.sort(Comparator.comparing(projectRefactorBugVo -> { try {Field field = projectRefactorBugVo.getClass().getSuperclass().getDeclaredField(queryDTO.getSortField()); field.setAccessible(true ); return (Comparable) field.get(projectRefactorBugVo);}catch (Exception e) { throw new RuntimeException(e);}}, Comparator.naturalOrder())); }else { voList.sort(Comparator.comparing(projectRefactorBugVo -> { try {Field field = projectRefactorBugVo.getClass().getSuperclass().getDeclaredField(queryDTO.getSortField()); field.setAccessible(true ); return (Comparable) field.get(projectRefactorBugVo);}catch (Exception e) { throw new RuntimeException(e);}}, Comparator.reverseOrder())); }
流,双层map 1 2 3 4 Map<String, Map<String, SysDictDataPlus>> dict = sysDictDataPlusService.list(queryWrapperSysDictDataPlus).stream().collect(Collectors.groupingBy( SysDictDataPlus::getDictType, Collectors.toMap(SysDictDataPlus::getDictValue, e -> e) ));
流map 1 2 3 4 Map<Long, List<RefactorReportInstance>> ins = instanceService.selectInstanceByInsIds(temIdList) .stream().collect(Collectors.groupingBy(RefactorReportInstance::getTemplateBaseId)); Map<Long, SysUser> usMap = userService.list().stream().collect(Collectors.toMap(SysUser::getUserId, t -> t));
流单map,单值过滤 1 2 3 4 5 6 7 8 9 10 11 Map<Long, RefactorReportInstance> collect = instanceService.selectInstanceByInsIds(temIdList).stream().collect(Collectors.toMap( RefactorReportInstance::getTemplateBaseId, e -> e, (exiValue, newValue) -> { return exiValue.getTemplateInstanceId() >= newValue.getTemplateInstanceId() ? exiValue : newValue; } )); Map<Long, RefactorReportInstance> temIns = instanceService.selectInstanceByInsIds(temIdList).stream().collect(Collectors.toMap( RefactorReportInstance::getTemplateBaseId,e -> e,(exiValue, newValue) -> exiValue.getTemplateInstanceId() >= newValue.getTemplateInstanceId() ? exiValue : newValue));
流,list分组 1 Map<Long, List<SysDept>> deptMapBytParentId = list.stream().collect(Collectors.groupingBy(SysDept::getParentId));
流,是否包含 1 boolean b = refactorReports.stream().anyMatch(person -> person.getTemplateInstanceId().equals(ins.getTemplateInstanceId()));
流,遍历修改list 1 2 3 4 5 6 7 8 9 10 11 List<RefactorReportContentTemplate> up = delRefactorReportContentTemplate.stream().peek(e -> { e.setDelFlag(CommonConstant.DELETED_BYTE); e.setUpdateTime(DateTimeUtil.getCurrentBeijingTime()); e.setUpdateBy(user.getUserName()); }).collect(Collectors.toList()); delRefactorReportContentTemplate = delRefactorReportContentTemplate.stream().peek(e -> { e.setDelFlag(CommonConstant.DELETED_BYTE); e.setUpdateTime(DateTimeUtil.getCurrentBeijingTime()); e.setUpdateBy(user.getUserName()); }).collect(Collectors.toList());
简单差集 1 2 3 List<Long> diff = reportCountUserIdList.stream() .filter(e -> !subUserIdList.contains(e)) .collect(Collectors.toList());
简单交集 1 2 3 4 5 6 7 List<Long> list1 = List.of(1L , 2L , 3L ); List<Long> list2 = List.of(2L , 3L , 4L ); List<Long> intersection = list1.stream() .filter(list2::contains) .distinct() .collect(Collectors.toList());
简单并集 1 2 A.addAll(B); List<String> AuB = A.stream().distinct().collect(Collectors.toList());
对象交集差集 现在有两个类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class ClassA { String id; String realName; public ClassA (String id, String realName) { this .id = id; this .realName = realName; } @Override public String toString () { return "ClassA{" + "id='" + id + '\'' + ", realName='" + realName + '\'' + '}' ; } public String getId () { return id; } public String getRealName () { return realName; } } class ClassB { String id; String nickName; public ClassB (String id, String nickName) { this .id = id; this .nickName = nickName; } @Override public String toString () { return "ClassB{" + "id='" + id + '\'' + ", nickName='" + nickName + '\'' + '}' ; } public String getId () { return id; } public String getNickName () { return nickName; } }
现在有两个集合,分别是ClassA对象的集合、ClassB对象的集合
1 2 3 4 5 6 7 8 9 10 11 List<ClassA> aList = new ArrayList<>(Arrays.asList( new ClassA("1" , "张三" ), new ClassA("2" , "李四" ), new ClassA("3" , "王五" ) )); List<ClassB> bList = new ArrayList<>(Arrays.asList( new ClassB("2" , "李某" ), new ClassB("3" , "王某" ), new ClassB("4" , "赵某" ) ));
基本思想就是想遍历第一个集合,取出第一个集合中的每个元素的某个属性,并使用这个属性遍历第二个集合,看这个属性是否在第二个集合中存在。相当于是有两层循环。 Java 8中引入了Stream和Lambda表达式,使用它们无需自己编写for循环,只需一行代码就能实现上述功能。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 List<ClassA> intersectA = aList .stream() .filter( a -> bList.stream() .map(ClassB::getId) .anyMatch( id -> Objects.equals(a.getId(), id) ) ) .collect(Collectors.toList()); System.out.println(intersectA);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 List<RefactorReportContentTemplate> upDateRefactorReportContentTemplate = oldContentTemplates.stream() .filter(a -> newContentTemplates.stream().map(RefactorReportContentTemplate::getId) .anyMatch(id -> Objects.equals(a.getId(), id))).collect(Collectors.toList()); List<RefactorReportContentTemplate> upDateRefactorReportContentTemplate = oldContentTemplates.stream() .filter(oldTemplate -> newContentTemplates.stream() .filter(e -> ObjectUtil.isNotEmpty(e.getId())) .anyMatch(newTemplate -> Objects.equals(oldTemplate.getId(), newTemplate.getId()) && ( !oldTemplate.getName().equals(newTemplate.getName()) || !oldTemplate.getStatus().equals(newTemplate.getStatus()) || !oldTemplate.getContentType().equals(newTemplate.getContentType()) || !oldTemplate.getPlaceholder().equals(newTemplate.getPlaceholder()) || !oldTemplate.getCannotEdit().equals(newTemplate.getCannotEdit()) ))).collect(Collectors.toList());
1 2 3 List<ClassB> differenceB = bList.stream().filter(b -> aList.stream().map(ClassA::getId).noneMatch(id -> Objects.equals(b.getId(), id))).collect(Collectors.toList()); System.out.println(differenceB);
简单去重 1 2 3 4 List<Long> makeDepts = new ArrayList<>(); makeDepts = makeDepts.stream().distinct().collect(Collectors.toList());
流类型转换,map 1 2 3 list(queryWrapperBing).stream().collect(Collectors.groupingBy( sysDataBindPlus -> Long.valueOf(sysDataBindPlus.getMainId()), Collectors.toList()));
1 Map<Long, List<RefactorReport>> collect = reportList.stream().collect(Collectors.groupingBy(RefactorReport::getTemplateInstanceId, Collectors.toList()));
1 2 Map<Long, User> userMap = userList.stream() .collect(Collectors.toMap(User::getId, t -> t));
转数组 1 2 long [] pos = sysUserPosts1.stream().mapToLong(SysUserPost::getPostId).toArray();Long[] pos = sysUserPosts1.stream().map(SysUserPost::getPostId).toArray(Long[]::new );
数组转list 1 List<Long> longList = Arrays.asList(longArray);
List,倒序 1 Collections.sort(voList, (s1, s2) -> s2.getState().compareTo(s1.getState()));
List,升序 1 Collections.sort(voList, Comparator.comparing(ProjectRefactorBugVo::getState));
1 2 3 4 5 if (Strings.isNotBlank(queryDTO.getSortField())) {if (ObjectUtil.isEmpty(queryDTO.getAsc()))queryDTO.setAsc(false ); queryWrapper.last("order by " + StrUtil.toUnderlineCase(queryDTO.getSortField()) + " " + ((queryDTO.getAsc()) ? "asc" : "desc" )); }
List 转字符串 1 String join = String.join(", " , list);
去除另外1个list中有的元素 1 2 3 4 newRole = newRole.stream() .filter(newRoleItem -> oldRole.stream() .noneMatch(oldRoleItem -> oldRoleItem.getRoleId().equals(newRoleItem.getRoleId()))) .collect(Collectors.toList());
本地懒得启动,就用远程调试。如果要一定要本地调试,就用 ktctl 引导 集群镜像一份流量 到 本地JVM