user5314029
user5314029

Reputation:

Frequency of object atribute value in ArrayList

This is my list:

List < Game > players = new ArrayList < > ();

I need to find out a way to calculate how many objects in ArrayList contain a name that equals to "Dan" for example.

I tried this in a for loop but doesn't work:

Collections.frequency(players.get( i ).name, "Dan")

Upvotes: 1

Views: 1220

Answers (2)

Bifz
Bifz

Reputation: 403

You should not do it this way, but if you really want to use Collections.frequency you need to implement the equals method in your Game class:

@Override
public boolean equals(Object o)
{
    if(o == null || !(o instanceof Player)) return false;
    Player p = (Player) o;
    return name.equals(p.getName());
}

Then you can call it with:

Game dan = new Game("dan");
Collections.frequency(players, dan);

(Maybe your Game class should be named Player)

Upvotes: 0

shmosel
shmosel

Reputation: 50716

Java 8 solution:

int count = players.stream()
        .filter(p -> p.name.equals("Dan"))
        .count();

Java 7 solution:

int count = 0;
for (Game player : players) {
    if (player.name.equals("Dan")) {
        count++;
    }
}

Upvotes: 4

Related Questions