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

3
  • Use a comparator, sort the list, retrieve the first element. Iterate through all elements and get the one with the highest. Commented Oct 5, 2013 at 5:20
  • docs.oracle.com/javase/7/docs/api/java/util/…, java.util.Comparator) Commented Oct 5, 2013 at 5:21
  • if you just have to find it once, just do a linear search. Commented Oct 5, 2013 at 6:01

2 Answers 2

5

Use max() with comparator

Collection.max(collection, customComparator);

Also See

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.