1. 一:对整数进行排序
  2. List<Integer> numbers =Arrays.asList(6,2,1,4,9);

  3. System.out.println(numbers);//[6, 2, 1, 4, 9]

  4. numbers.sort(Comparator.naturalOrder());

  5. System.out.println(numbers);//[1, 2, 4, 6, 9]

  6. 二、按字符串字段对列表进行排序
    1. List<Movie> movies =Arrays.asList(

    2. newMovie("Lord of the rings"),

    3. newMovie("Back to the future"),

    4. newMovie("Carlito's way"),

    5. newMovie("Pulp fiction"));

    6. movies.sort(Comparator.comparing(Movie::getTitle));

    7. movies.forEach(System.out::println);

    8. 提取的类型是String,而String实现了 Comparable接口,所以list能正确排序。
    9. 三、按double字段排序列表

    10. List<Movie> movies =Arrays.asList(

    11. newMovie("Lord of the rings",8.8),

    12. newMovie("Back to the future",8.5),

    13. newMovie("Carlito's way",7.9),

    14. newMovie("Pulp fiction",8.9));

    15. movies.sort(Comparator.comparingDouble(Movie::getRating)

    16. .reversed());

    17. movies.forEach(System.out::println);

    18. 我们使用反转函数( reversed)来反转默认从低到高的自然排序, Comparator.comparingDouble() 底层使用 Double.compare()实现。如果需要比较 intlong,可以分别使用 comparisonInt()comparisonLong()
    19. 四、使用自定义比较器多列表进行排序
      1. List<Movie> movies =Arrays.asList(

      2. newMovie("Lord of the rings",8.8,true),

      3. newMovie("Back to the future",8.5,false),

      4. newMovie("Carlito's way",7.9,true),

      5. newMovie("Pulp fiction",8.9,false));

      6. movies.sort(newComparator<Movie>(){

      7. @Override

      8. publicint compare(Movie m1,Movie m2){

      9. if(m1.getStarred()== m2.getStarred()){

      10. return0;

      11. }

      12. return m1.getStarred()?-1:1;

      13. }

      14. });

      15. 我们可以使用 lambda表达式而不是匿名类( Anonymousclass),如下所示:
      16. movies.forEach(System.out::println);

        1. movies.sort((m1, m2)->{

        2. if(m1.getStarred()== m2.getStarred()){

        3. return0;

        4. }

        5. return m1.getStarred()?-1:1;

        6. });

        7. 也可以使用 Comparator.comparing():
          1. movies.sort(Comparator.comparing(Movie::getStarred,(star1, star2)->{

          2. if(star1 == star2){

          3. return0;

          4. }

          5. return star1 ?-1:1;

          6. }));

  1. List<Integer> numbers =Arrays.asList(6,2,1,4,9);

  2. System.out.println(numbers);//[6, 2, 1, 4, 9]

  3. numbers.sort(Comparator.naturalOrder());

  4. System.out.println(numbers);//[1, 2, 4, 6, 9]

 

 

 

原文链接:https://dzone.com/articles/java-8-comparator-how-to-sort-a-list

 

作者: Mario Pio Gioiosa

 

译者:Steephan

 

 posted on 2019-05-30 09:32  sunnyBalckCat  阅读(1824)  评论(0编辑  收藏  举报