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.