Check for value in collection
I'm trying to check a collection for a particular value
开发者_运维百科i.e. I want to check the collection of players for a positionType = attacker. It does not matter how man references, as long as there is at least one.
Every attempt so far has failed me.
Any ideas?
Thanks in advance!
public Player findFirstAttacker(Collection<Player> players) {
for (Player p : players) {
if (p.getPositionType() == Player.POSITION_ATTACKER) {
return p;
}
}
return null;
}
Did you try the Collection.contains() method?
If so, and it was returning the wrong answer, check that the implementations of equals()
and hashCode()
on the class of the player are appropriate. These methods will (probably) be used to check whether the collection contents are equal to the object you pass in, so if they are left as the default implementations inherited from Object
you may not get the behaviour you expect.
guava has:
boolean hasAttackers = Iterables.any(list, new Predicate<Player>() {
public boolean apply(Player player) {
return player.getPosition().equals(PositionType.ATTACKER);
}
});
public Player getFirstAttacker(Collection<Player> playerCollection) {
for (Player player : playerCollection) {
if (player.getPosition() == Position.attacker) {
return player;
}
}
return null;
}
精彩评论