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

后端 未结 4 1546
花落未央
花落未央 2021-01-03 00:12

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 la

4条回答
  •  礼貌的吻别
    2021-01-03 00:54

    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 playerList = new ArrayList();
    
    
    public static void sortPlayers(List playerList) {
       Collections.sort(playerList, new Comparator() {
           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())
           }
       });
    }
    

提交回复
热议问题