Sorting an ArrayList of Objects by Last name and firstname in Java

Change the comparator to:

            public int compare(Object o1, Object o2) {
                PlayerStats p1 = (PlayerStats) o1;
                PlayerStats p2 = (PlayerStats) o2;
                int res =  p1.getPlayerLastName().compareToIgnoreCase(p2.getPlayerLastName());
                if (res != 0)
                    return res;
                return p1.getPlayerFirstName().compareToIgnoreCase(p2.getPlayerFirstName())
            }

Petar's answer is correct, just two remarks:

  • Use List instead of ArrayList as method argument, as the interface is more general, and the method will work even if you change to another List type (like LinkedList... ) later
  • Use generics to make your code more type safe.

An improved version:

//the place where you define the List
List<PlayerStats> playerList = new ArrayList<PlayerStats>();


public static void sortPlayers(List<PlayerStats> playerList) {
   Collections.sort(playerList, new Comparator<PlayerStats>() {
       public int compare(PlayerStats p1, PlayerStats p2) {
            int res =  p1.getPlayerLastName().compareToIgnoreCase(p2.getPlayerLastName());
            if (res != 0)
                return res;
            return p1.getPlayerFirstName().compareToIgnoreCase(p2.getPlayerFirstName())
       }
   });
}

Using java8 there is easy way to do this:

public List<PlayerStats> getSortedPlayerList(List<PlayerStats> playerList) {
    return playerList.stream().sorted(Comparator.comparing(PlayerStats::getPlayerLastName).thenComparing(PlayerStats::getPlayerFirstName)).collect(Collectors.toList());
}

Tags:

Java