0

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

user2343837
  • 1,005
  • 5
  • 20
  • 31

2 Answers2

5

Use max() with comparator

Collection.max(collection, customComparator);

Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
2

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);
Vijay
  • 1,024
  • 6
  • 18