How to sort an ArrayList?

后端 未结 20 2405
有刺的猬
有刺的猬 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:41

    With Eclipse Collections you could create a primitive double list, sort it and then reverse it to put it in descending order. This approach would avoid boxing the doubles.

    MutableDoubleList doubleList =
        DoubleLists.mutable.with(
            0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
            0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
            .sortThis().reverseThis();
    doubleList.each(System.out::println);
    

    If you want a List, then the following would work.

    List objectList =
        Lists.mutable.with(
            0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
            0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
            .sortThis(Collections.reverseOrder());
    objectList.forEach(System.out::println);
    

    If you want to keep the type as ArrayList, you can initialize and sort the list using the ArrayListIterate utility class as follows:

    ArrayList arrayList =
        ArrayListIterate.sortThis(
                new ArrayList<>(objectList), Collections.reverseOrder());
    arrayList.forEach(System.out::println);
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题