Duy Luc
Duy Luc

Reputation: 21

how to get frequency of Object's field in ArrayList

I try this code to print out the frequency of name "John"in the list(Human has 2 field: name and age):

package test;
import data.Boy;
import data.Human;
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    List<Human> menu = new ArrayList();
       menu.add(new Human("John",20));
       menu.add(new Human("Smith",19));
       menu.add(new Human("Alice",12));
       menu.add(new Human("John",18));
       System.out.println(Collections.frequency(menu, menu.get(0).getName());

}
}

But the value is 0 instead of 2.Which's wrong in this code?

Upvotes: 0

Views: 1808

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

Collections#frequency would be appropriate if you wanted to count how many times a particular Human object appeared in your list. But you want to check the count of humans having a particular name, regardless of whether that name might occur in more than one object. Streams come in handy here:

List<Human> matches = menu.stream()
                          .filter(h -> h.getName().equals(menu.get(0).getName()))
                          .collect(Collectors.toList());

int size = matches == null ? 0 : matches.size();
System.out.println("There are " + size + " humans which match.");

Upvotes: 2

terryk
terryk

Reputation: 116

Well, menu contains Human objects, not Strings, which is what's presumably returned by getName(). Therefore, Collections.frequency() will check if menu contains "John", but it doesn't - it instead contains a Human with the name "John".

Upvotes: 0

Related Questions