list排序的几种方法

  • A+
所属分类:Java

 List<Integer> list = new ArrayList<>();

 list.add(3);

 list.add(5);

 list.add(1);

Collections工具类,升序排:

Collections.sort(list);

System.out.println(list);

Console:

[1, 3, 5]

Collections工具类,降序排:

Collections.reverse(list);

System.out.println(list);

Console:

[5, 3, 1]

java8新特性,升序排:

list.sort(Integer::compareTo);

list.stream().sorted((a,b)->a.compareTo(b)).forEach(System.out::println);

list.stream().sorted(Comparator.naturalOrder()).forEach(System.out::println);

System.out.println(list);

也可以使用自定义排序如下,效果一样,不过不够简洁

list.sort(new Comparator<Integer>() {

            @Override

            public int compare(Integer o1, Integer o2) {

                return o1-o2;

            }

        });

Console:

[1, 3, 5]

自定义排序,降序排:

 list.sort(new Comparator<Integer>() {

       @Override

       public int compare(Integer o1, Integer o2) {

           return o2-o1;

       }

 });

 list.stream().sorted((a,b)->b.compareTo(a)).forEach(System.out::println);

 list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

 System.out.println(list);

Console:

[5, 3, 1]

值得注意的是sorted只是创建一个流对象排序的视图,而不会改变原集合中元素的顺序。也就是说使用sorted方法原有集合的顺序实际上是没有发生变化的。

 

补充: 针对集合中存在null的几种排序及测试结果。

    @Test

    public void sort() {

        List<Integer> list = Lists.newArrayList();

        list.add(1);

        list.add(3);

        list.add(2);

        list.add(null);

 

        Ordering<Comparable> natural = Ordering.natural();

        Collections.sort(list, natural.nullsLast());

        System.out.println("list = " + list);

        // list = [1, 2, 3, null]

 

        Collections.sort(list, natural.nullsFirst());

        System.out.println("list = " + list);

        // list = [null, 1, 2, 3]

 

        list.removeIf(e -> Objects.isNull(e));

        Collections.sort(list);

        System.out.println("list = " + list);

        // list = [1, 2, 3]

    }

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: