Java:如何按大小对多个 ArrayList 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3477272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How do I sort multiple ArrayList by their size?
提问by user419596
I have 9 different ArrayListand I want to have a list of the top 5.
我有 9 个不同的ArrayList,我想列出前 5 个。
I'm thinking of sorting those ArrayListsby their sizes.
我正在考虑ArrayLists按大小对它们进行排序。
Is it possible to do that? If so, how can I achieve that?
有可能这样做吗?如果是这样,我怎样才能做到这一点?
After a few try i finally got it working, just want to share it with everyone.
经过几次尝试,我终于成功了,只是想与大家分享。
it will be better to get the size of the arraylist and add it to the big arraylist
获取arraylist的大小并将其添加到大arraylist会更好
// creates an ArrayList that holds ArrayLists
List allTheLists = new ArrayList();
allTheLists.add(pbaustraliaList.size());
allTheLists.add(pbotherList.size());
allTheLists.add(pbunitedStatesList.size());
allTheLists.add(pbunitedKingdomList.size());
allTheLists.add(pbchinaList.size());
allTheLists.add(pbgermanyList.size());
allTheLists.add(pbindiaList.size());
allTheLists.add(pbjapanList.size());
allTheLists.add(pbsingaporeList.size());
Comparator comparator = Collections.reverseOrder();
Collections.sort(allTheLists,comparator);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in descending order : ");
for(int i=0; i<allTheLists.size(); i++) {
System.out.println(allTheLists.get(i));
}
回答by jjnguy
What you could do is the following:
您可以执行以下操作:
// this List of lists will need to contain
// all of the ArrayLists you would like to sort
List<ArrayList> allTheLists;
Collections.sort(allTheLists, new Comparator<ArrayList>(){
public int compare(ArrayList a1, ArrayList a2) {
return a2.size() - a1.size(); // assumes you want biggest to smallest
}
});
This will sort the list of lists by the length of each list. The first element in the sorted list will be the longest list, and the last one will be the shortest list.
这将按每个列表的长度对列表列表进行排序。排序列表中的第一个元素将是最长的列表,最后一个元素将是最短的列表。
Then, you can iterate through the first 5 lists to see what the top 5 were.
然后,您可以遍历前 5 个列表以查看前 5 个列表。
Some links for reference:
一些链接供参考:
Depending on how you have your ArrayListsstored, the code to create a List<ArrayList>would look something like this:
根据您的ArrayLists存储方式,创建 a 的代码List<ArrayList>如下所示:
// creates an ArrayList that holds ArrayLists
List<ArrayList> allTheLists = new ArrayList<ArrayList>();
allTheLists.add(yourList1);
allTheLists.add(yourList2);
...
allTheLists.add(yourList9);
回答by Sadhna Juhirdeen
you can do like this as well
你也可以这样做
public static <T> List<List<T>> sort(List<List<T>> list) {
list.sort((xs1, xs2) -> xs1.size() - xs2.size());
return list;
}

