我想知道是否可以使用单个Java Steam语句打印出集合中的唯一元素,并包括每个元素的计数。
例如,如果我有:
List<String> animals = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog");我想要打印流:
cat - 1
dog - 2
pony - 3发布于 2018-08-16 00:03:38
你可以这样做,
Map<String, Long> result = animals.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));使用Collectors.groupingBy对具有相同键的元素进行分组。然后,对每个组应用counting下游收集器以获取计数。
发布于 2018-08-16 00:03:50
您可以组合分组和计数收集器:
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}https://stackoverflow.com/questions/51862238
复制相似问题