项目中使用到的集合
一、List 集合截取部分内容
userList = userList .subList(5,10);
截取 userList [5,10) 条数据
二、将有序的集合打乱(变为乱序)
Collections.shuffle(userList);
将userList 内容的元素打乱
三、将两个List 集合合并为一个,并去重
list01.removeAll(list02);
list01.addAll(list02);
四、将集合,按照某个属性进行合并
List<Student> list = new ArrayList<>(); list.add(new Student(1,"张三",10,50)); list.add(new Student(2,"李四",20,20)); list.add(new Student(3,"张三",30,30)); list.add(new Student(1,"李四",40,40)); List<Student> studentList = new ArrayList<>(); list.stream().collect(Collectors.groupingBy(Student::getId,Collectors.toList())) .forEach((id,transfer)->{ transfer.stream().reduce((a,b)->new Student(a.getId(),a.getName(),a.getAge()+b.getAge(),a.getAge2()+b.getAge2())).ifPresent(studentList::add); }); studentList.forEach(e->System.out.println(e));
五、对集合中某一列属性求和
方法一
Integer totalStarCnt = starCntList.stream()
.collect(Collectors.summingInt(CommentStarCntVO::getNumber));
方法二
Integer totalStarCnt = starCntList.stream()
.mapToInt(CommentStarCntVO::getNumber).sum();
六、求集合中某俩列乘积再求和
Double ss = orderList.stream().reduce(0.0, (x, y) -> x + (y.getNum() * y.getPrice()), Double::sum);
七、集合提取某个唯一属性作为key,转换为Map
Map<Long,FxUserSimpleDTO> fxMap = fxUserSimpleDTOList.stream()
.collect(Collectors.toMap(FxUserSimpleDTO::getUid,Function.identity()));
八、将List 集合中实体的2个属性作为 key-value ,转换为 Map
List<Student> list = Arrays.asList( new Student(1,"",20), new Student(2,"",30), new Student(3,"",40), new Student(4,"",50) ); Map<Integer,Integer> studentMap = list.stream() .collect(Collectors.toMap(Student::getId,Student::getAge)); for(Map.Entry<Integer,Integer> entry : studentMap.entrySet()){ System.out.println(entry); }
九、将 List 数组中对象,按照某个属性进行分组。
List<Student> list = Arrays.asList( new Student(1,"1.jpg",20), new Student(2,"2.jpg",30), new Student(2,"3.jpg",40), new Student(1,"4.jpg",50) ); Map<Integer, List<Student>> listMap = list.stream() .collect(Collectors.groupingBy(Student::getId,Collectors.toList())); for(Map.Entry<Integer, List<Student>> entry: listMap.entrySet()){ System.out.println(entry.getKey()); System.out.println(entry.getValue()); }
集合转换参考:https://blog.csdn.net/codeissodifficulty/article/details/88864358
集合合并参考:https://blog.csdn.net/qq_36850813/article/details/106117908