How to sort an ArrayList?

后端 未结 20 2447
有刺的猬
有刺的猬 2020-11-22 06:19

I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List testList = new Arr         


        
20条回答
  •  爱一瞬间的悲伤
    2020-11-22 06:40

    For your example, this will do the magic in Java 8

    List testList = new ArrayList();
    testList.sort(Comparator.naturalOrder());
    

    But if you want to sort by some of the fields of the object you are sorting, you can do it easily by:

    testList.sort(Comparator.comparing(ClassName::getFieldName));
    

    or

     testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());
    

    or

     testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());
    

    Sources: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

提交回复
热议问题