How to sort Arraylist of objects

前端 未结 3 1360
星月不相逢
星月不相逢 2020-12-03 05:42

I have ArrayList, which containst football teams (class Team). Teams have points and i want to sort them by number of points.

 public class Team {
     priva         


        
3条回答
  •  無奈伤痛
    2020-12-03 06:06

    It is not actually necessary to define a custom Comparator like this.

    Instead, you can easily define one, when you want to sort your ArrayList.

    Since JAVA 8 using lamda

        // Sort version.
        Iteams.sort(Comparator.comparing(Team::getPoints));
    
        // Complete version.
        Iteams.sort((o1, o2) -> o1.getPoints().compareTo(o2.getPoints()));
    


    Also there are options for second comparator, if objects are equals on the first:

        // e.g. if same points, then compare their names.
        Iteams.sort(Comparator.comparing(Team::getPoints).thenComparing(Team::getName));
    


    Also note that the default sort option is ascending, but you can set it to descending using:

        // e.g. Sort by points descending.
        Iteams.sort(Comparator.comparing(Team::getPoints).reversed());
    


    That way, you can sort your ArrayList in different ways whenever you want, just by adding the method you want.

提交回复
热议问题