List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//统计集合的最大值,最小值,总和,平均值等
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println(stats);
//统计个数
Map<Integer, List<Integer>> collect = numbers.stream().collect(Collectors.groupingBy(Integer::intValue));
for (Map.Entry<Integer, List<Integer>> integerListEntry : collect.entrySet()) {
System.out.println(integerListEntry.getKey() +" > " +integerListEntry.getValue().size());
}
System.out.println("====================");
//字符串拆分成list,统计个数,再倒序排序
String str = "aaabbcccaccbbbbb";
List<Map.Entry<String, Integer>> strCountList =
Arrays.stream(str.trim().split("")).collect(Collectors
.groupingBy(st -> st,
Collectors.collectingAndThen(Collectors.toList(), List::size))).entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue()
.reversed()).collect(Collectors.toList());
//统计元素出现次数做多的
strCountList.stream().findFirst().ifPresent(entry ->
System.out.println("字母{" + entry.getKey() + "}出现的次数最多,出现{" + entry.getValue() + "}次"));
for (Map.Entry<String, Integer> stringIntegerEntry : strCountList) {
System.out.println(stringIntegerEntry.getKey() +" > " +stringIntegerEntry.getValue());
}
//字符串List统计个数
List<String> list = Arrays.asList("zhangsan","lisi","wangbninwei","zhangsan","zhangsan","wangbninwei","留底","test");
Map<String, Integer> collectName = list.stream().collect(Collectors.groupingBy(name -> name, Collectors.collectingAndThen(Collectors.toList(), List::size)));
System.out.println(collectName);
java8 Stream
最新推荐文章于 2024-09-02 20:52:37 发布