Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java CompareTo Sorting - Sorting Multiple Fields for Same Object

I have an ArrayList of objects - Player, and I currently have the code to sort by its field, last name. Player has an additional field, height, which I need to sort by in other areas of the application.

I believe I understand that overriding the compareTo gives the information to the sort method of field it's sorting on. Since I need to sort with two different fields (not at the same time, but for separate applications), what is the best way to approach this? See the code below for context.

public class Player implements Comparable<Player>

  @Override
  public int compareTo(Player object) {
      Player other = (Player) object;
      // We always want to sort by last name then first name
    if(equals(other)) {
    return 0;
    }
    return lastName.compareTo(other.lastName);
  }

Collections.sort(team.getPlayerList());

1 Answer

I figured this out, I needed to utilize comparators. Here is a good resource: https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

import java.util.Comparator;

``` public static Comparator<Player> playerHeightComparator = new Comparator<Player>() { public int compare(Player p1, Player p2) { Integer playerHeight1 = p1.getHeightInInches(); Integer playerHeight2 = p2.getHeightInInches(); return playerHeight1.compareTo(playerHeight2); } };

public static Comparator<Player> playerLastNameComparator = new Comparator<Player>() {
    public int compare(Player p1, Player p2) {
        String playerName1 = p1.getLastName();
        String playerName2 = p2.getLastName();
        return playerName1.compareTo(playerName2);
    }
};
`Collections.sort(height3540, Player.playerHeightComparator);`