1.list分组统计个数
String content = "2022-02-17-2022-02-18-2022";
//将字符串转换为list集合
List<String> strings = Arrays.asList(content.split("-"));
//使用stream流分组并统计每个元素出现的个数
Map<String, Long> map = strings.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
//打印输出
map.forEach((k,v)->System.out.println(k+"====="+v));
2.常用数据处理求和最大最下平均值
//reduce求和
Integer integer = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).reduce((a0, a1) -> {
return a0 + a1;
}).get();
System.out.println(integer);
//sum求和
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).mapToInt(Integer::intValue).sum());
//求最大值
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).mapToInt(Integer::intValue).max().getAsInt());
//求最小值
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).mapToInt(Integer::intValue).min().getAsInt());
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).min((s1, s2) -> Integer.compare(s1, s2)).get());
//求平均值
System.out.println(Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).mapToInt(Integer::intValue).average().getAsDouble());
3.排序
//排序(升序)
System.out.println(Stream.of(2,1,3,5,4,6,8,9,7).sorted().collect(Collectors.toList()));
//排序(降序)
System.out.println(Stream.of(2,1,3,5,4,6,8,9,7).sorted(Comparator.reverseOrder()).collect(Collectors.toList()));
//通过stream流排序 多字段排序 并且注意空值问题
//先按照Distance字段升序排列空值放在最下面,在按照BuildArea字段降序排列空值放在最下面
dataInfos.parallelStream()
.sorted(Comparator.comparing(DataInfo::getDistance,Comparator.nullsLast(Double::compareTo)).thenComparing(DataInfo::getBuildArea,Comparator.nullsFirst(Integer::compareTo).reversed()))
.collect(Collectors.toList()).forEach(System.out::println);
//通过stream流排序多字段排序 但是不注意空值问题
//先按照Distance字段升序排列面,在按照BuildArea字段降序排列
dataInfos.stream()
.sorted(Comparator.comparing(DataInfo::getDistance).thenComparing(DataInfo::getBuildArea,Comparator.reverseOrder()))
.collect(Collectors.toList()).forEach(System.out::println);
4.分组求和
Student student1 = new Student(1, 1);
Student student2 = new Student(1, 1);
Student student3 = new Student(2, 2);
Student student4 = new Student(2, 3);
Student student5 = new Student(3, 3);
Student student6 = new Student(3, 4);
Student student7 = new Student(4, 1);
List<Student> list = Arrays.asList(student1, student2, student3, student4, student5, student6, student7);
//按照id进行分组,并且对每组分数求和
Map<Integer, Integer> collect = list.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summingInt(Student::getScore)));
System.out.println(collect)
5.获取id最小的用户
User maxId = userList.stream().collect(Collectors.minBy(Comparator.comparingInt(User::getId))).get() ;