user2343837
user2343837

Reputation: 1015

Find an object inside ArrayList Java

I have an ArrayList of objects. Each object is of type Player (one of the classes that I have). Each Player object has a getName() method and a getValue() method. The getValue method is of integer type. All the Player objects go into an ArrayList, listOfPlayers. How do I find a PLayer object with the highest getValue()?

I know there is a method called Collections.max(), but for me it only seems to work if the ArrayList is just full of integers.

Thanks

Upvotes: 0

Views: 1475

Answers (2)

Vijay
Vijay

Reputation: 1034

You need to Implement Comparator for your class like this

Comparator<Player> cmp = new Comparator<Player>() {
    @Override
    public int compare(Player o1, Player o2) {
        return Integer.valueOf(o1.getValue()).compareTo(Integer.valueOf(o2.getValue()));
    }
};

then call

  Collections.max(listOfPlayers, cmp);

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240900

Use max() with comparator

Collection.max(collection, customComparator);

Also See

Upvotes: 5

Related Questions