Marco Berrocal
Marco Berrocal

Reputation: 362

Sort ArrayList of objects through one of its instance variables

Helllo,

I have an ArrayList of OBJECTS (teams). They are football teams and I would like to sort them out through their points. Obviously I am fully aware ArrayLists are sorted via the order they are inserted.

But I have a TEAM class that has gamesWon, gamesLost, gamesTied and points based on a match result.

I have everything ready but figured that sorting out an ArrayList through it's points would be a cool feature to make.

I have read the Collections.sort(myArrayList) online, but this sorts based on ONE type of variable, and since I have objects within the ArrayList, I would like to sort this out.

Thank you.

Marco

Upvotes: 0

Views: 2374

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You should define a Comparator for this.

public class PointsBasedTeamComparator implements Comparator<Team> {
    public int compare(Team t1, Team t2) {
        //return the result of points comparison of t1 and t2
    }
}

And use it as follows

Collections.sort(teams, new PointsBasedTeamComparator());

Upvotes: 3

SJuan76
SJuan76

Reputation: 24780

  1. Define a java.util.Comparator<Team> that implements compareTo with the value that you want to check.

  2. Use the sort method that accepts the Comparator<Object>. It will use the compareTo method of your Comparator, and not the one defined in Team (if any).

  3. Enjoy!

Upvotes: 2

Related Questions