lyancsie
lyancsie

Reputation: 678

Collecting occurrences in a HashMap with streams

I've got an exercise to solve. I've got a Fox class, which has got name and color fields. My exercise is to find the frequency of the foxes by color.

Thus I've created a HashMap, where the String attribute would be the fox name and the Integer would be the occurrence itself:

    Map<String, Integer> freq = new HashMap<>();

Having done that, I have been trying to write the code with streams, but I am struggling to do that. I wrote something like this:

    foxes.stream()
    .map(Fox::getColor)
    .forEach()
    //...(continued later on);

, where foxes is a List.

My problem is basically with the syntax. I'd like to do something that if the color has no occurrences then

    freq.put(Fox::getName, 1)

else

    freq.replace(Fox::getName, freq.get(Fox::getName) + 1)

How should I put it together?

Upvotes: 1

Views: 382

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

I wouldn't suggest proceeding with your approach simply because there is already a built in the collector for this i.e. groupingBy collector with counting() as downstream:

 Map<String, Long> result = foxes.stream()
      .collect(Collectors.groupingBy(Fox::getName, Collectors.counting()));

This finds the frequency by "name", likewise, you can get the frequency by colour by changing the classification function.

foxes.stream()
     .collect(Collectors.groupingBy(Fox::getColor, Collectors.counting()));

Upvotes: 6

Related Questions