How to sort List? [duplicate]

2020-05-21 12:09发布

I have code and I have used list to store data. I want to sort data of it, then is there any way to sort data or shall I have to sort it manually by comparing all data?

import java.util.ArrayList; 
import java.util.List;

public class tes
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
    }
}

7条回答
够拽才男人
2楼-- · 2020-05-21 12:44

To sort in ascending order :

Collections.sort(lList);

And for reverse order :

Collections.reverse(lList);
查看更多
老娘就宠你
3楼-- · 2020-05-21 12:54

Use Collections class API to sort.

Collections.sort(list);
查看更多
Deceive 欺骗
4楼-- · 2020-05-21 12:56

You can use the utility method in Collections class public static <T extends Comparable<? super T>> void sort(List<T> list) or

public static <T> void sort(List<T> list,Comparator<? super T> c)

Refer to Comparable and Comparator interfaces for more flexibility on sorting the object.

查看更多
看我几分像从前
5楼-- · 2020-05-21 13:03

Just use Collections.sort(yourListHere) here to sort.

You can read more about Collections from here.

查看更多
时光不老,我们不散
6楼-- · 2020-05-21 13:04

You can use Collections for to sort data:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

public class tes
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();

        lList.add(4);       
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);

        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }

    }
}
查看更多
孤傲高冷的网名
7楼-- · 2020-05-21 13:10

Ascending order:

 Collections.sort(lList); 

Descending order:

Collections.sort(lList, Collections.reverseOrder()); 
查看更多
登录 后发表回答