List Distinct elements including a count with Java Streams

user2440671 :

I'm wondering if it's possible to use a single Java Steam statement to print out the unique elements in a collection and include the count for each element.

For example, if I had:

List<String> animals = Arrays.asList("dog", "cat", "pony", "pony", "pony", "dog");

I'd want the stream to print:

cat - 1
dog - 2
pony - 3
Ravindra Ranwala :

You may do it like so,

Map<String, Long> result = animals.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Use Collectors.groupingBy to group the elements with the same key. Then apply the counting down stream collector for each group to get the count.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111696&siteId=1