package com.my.app.stream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Description 统计次数,并按次数高低进行输出
*/
public class Count {
public static void main(String[] args) {
String[] names = {"张三", "张三", "李四", "李四", "李四", "李四", "王五", "A", "B", "C", "C"};
// 仅输出按次数排序后的元素
List<String> finalList = Stream.of(names)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted((v1, v2) -> v2.getValue().compareTo(v1.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(finalList);
// 输出按次数排序后的元素和次数
Map<String, Long> finalMap = Stream.of(names)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted((v1, v2) -> v2.getValue().compareTo(v1.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m1, m2) -> m2,
LinkedHashMap::new));
System.out.println(finalMap);
}
}
输出结果:
[李四, 张三, C, A, B, 王五]
{李四=4, 张三=2, C=2, A=1, B=1, 王五=1}