How to sort an ArrayList?

I have a List of doubles in java and I want sorted ArrayList in descending order

Input ArrayList is like-

  List<Double> testList=new ArrayList();

    testList.add(0.5);
    testList.add(0.2);
    testList.add(0.9);
    testList.add(0.1);
    testList.add(0.1);
    testList.add(0.1);
    testList.add(0.54);
    testList.add(0.71);
    testList.add(0.71);
    testList.add(0.71);
    testList.add(0.92);
    testList.add(0.12);
    testList.add(0.65);
    testList.add(0.34);
    testList.add(0.62);

The out put should be like this

0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1  

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Here is the documentation for Collections .


Use util method of java.util.Collections class, ie

Collections.sort(list)

In fact, if you want to sort custom object you can use

Collections.sort(List<T> list, Comparator<? super T> c) 

see collections api


降:

Collections.sort(mArrayList, new Comparator<CustomData>() {
    @Override
    public int compare(CustomData lhs, CustomData rhs) {
        // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
        return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
    }
});
链接地址: http://www.djcxy.com/p/19990.html

上一篇: 如何获取Python中的所有直接子目录

下一篇: 如何排序ArrayList?