Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I have an arrayList of different types of players based on sports. I need to sort the list of players in the arrayList by last name to start. If 2 players have the same last name it needs to then sort those 2 players by the first name. example: Format Lastname firstname

Williams Robert
Phillips Warren
Doe John
Phillips Mark

Output should be

Doe John
Phillips Mark
Phillips Warren
Williams Robert

What I have now only sorts by either the first or last. I have it by last atm in my code.

public static void sortPlayers(ArrayList playerList) {
    for (int i = 0; i < playerList.size(); i++) {
        for (int j = 0; j < playerList.size(); j++) {
            Collections.sort(playerList, new Comparator() {

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

    }
}
like image 794
Jeremy Avatar asked Jul 16 '11 21:07

Jeremy


People also ask

Can you sort an ArrayList of objects in Java?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

How do you sort an ArrayList by name?

To sort the ArrayList, you need to simply call the Collections. sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order).

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.

How do you sort an ArrayList of objects in Java 8?

– Use Collections. sort() method for sorting the ArrayList in-place, or Java 8 Stream. sorted() to return a new sorted ArrayList of Objects (the original List will not be modified). – For Descending order, just pass Collections.


2 Answers

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())
}
like image 172
Petar Ivanov Avatar answered Sep 20 '22 03:09

Petar Ivanov


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())
       }
   });
}
like image 38
Landei Avatar answered Sep 19 '22 03:09

Landei