列出不同的元素,包括 Java 流的计数
List Distinct elements including a count with Java Streams
我想知道是否可以使用单个 Java Steam 语句打印出集合中的独特元素并包括每个元素的计数。
例如,如果我有:
List<String> animals = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog");
我想要打印流:
cat - 1
dog - 2
pony - 3
你可以这样做,
Map<String, Long> result = animals.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
使用Collectors.groupingBy
将具有相同键的元素分组。然后为每个组应用 counting
下游收集器以获取计数。
您可以组合分组和计数收集器:
Map<String, Long> countMap = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog")
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
这导致这张地图:
{cat=1, dog=2, pony=3}
我想知道是否可以使用单个 Java Steam 语句打印出集合中的独特元素并包括每个元素的计数。
例如,如果我有:
List<String> animals = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog");
我想要打印流:
cat - 1
dog - 2
pony - 3
你可以这样做,
Map<String, Long> result = animals.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
使用Collectors.groupingBy
将具有相同键的元素分组。然后为每个组应用 counting
下游收集器以获取计数。
您可以组合分组和计数收集器:
Map<String, Long> countMap = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog")
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
这导致这张地图:
{cat=1, dog=2, pony=3}