1

For example i have a list:

ArrayList<Observer> arrlist = new ArrayList<Observer>();

The list contains the observer objects but i want to know the frequency of objects that have the same value for example String name

    public class  Observer{
    private String name;
}

How do i do that?

Imatabil
  • 19
  • 1
  • 5
  • 6
    Does this answer your question? [How to count the number of occurrences of an element in a List](https://stackoverflow.com/questions/505928/how-to-count-the-number-of-occurrences-of-an-element-in-a-list) – gkhaos May 03 '21 at 09:26
  • no,because there are Strings and can be resolved just with Java Collections frequency() Method – Imatabil May 03 '21 at 09:32

1 Answers1

0

You basically need to iterate over the observers and count the occurence for each key (could be just a single property or a combination depending on your needs).

Taking your example of the key just being Observer.name you could do the following:

Map<String, List<Observer>> observersByName = 
       arrlist.stream().collect(Collectors.groupingBy(Observer::getName));

Then iterate over the entry set and call size() on the value lists to get the frequency.

If you directly want to get the frequency, add a counting() collector:

Map<String, Long> nameFrequency = arrlist.stream().collect(
                                     Collectors.groupingBy(Observer::getName,
                                                           Collectors.counting()));

If you want to get the frequency without using streams you could use the Map.merge() method:

Map<String, Integer> nameFrequency = new HashMap<>();
for( Observer obs : arrlist ) {
   //use the name as the key, associate a value of 1 with each key
   //if an entry already existed merge existing and new value by summing them
   frequency.merge( obs.getName(), 1, Integer::sum);
}
Thomas
  • 87,414
  • 12
  • 119
  • 157