[英]Java sort LinkedList of LinkedLists into size order
I'm currently faced with this problem: I have a LinkedList that contains several LinkedLists containing longs, so: 我目前面临这个问题:我有一个LinkedList,其中包含多个包含long的LinkedList,因此:
LinkedList<LinkedList<Long>>() overalllList = new LinkedList<LinkedList<Long>();
After some code runs, the overall List gets filled with lists of longs of varying sizes. 运行一些代码后,整个列表将填充各种大小的long列表。 What I need to do is order the overallList so that it contains the lists of longs from smallest to largest.
我需要做的是对总体清单进行排序,以便它包含从最小到最大的多头清单。
I hope that makes sense. 我希望这是有道理的。
So to clarify, I need this: 因此,我需要澄清一下:
OverallList:
LinkedList<Long> (size 2) - first
LinkedList<Long> (size 245) - second
LinkedList<Long> (size 1000) - third
...etc
I'm not sure if using Collections would do this, or if I need to look at a custom comparator. 我不确定使用Collections是否可以做到这一点,或者我是否需要查看自定义比较器。 Any input or advice would be appreciated.
任何意见或建议,将不胜感激。
Thanks 谢谢
Here is one example of a method to do that, 这是一种方法的示例,
// A "size()" comparator
private static Comparator<LinkedList<Long>> comp = new Comparator<LinkedList<Long>>() {
@Override
public int compare(LinkedList<Long> o1, LinkedList<Long> o2) {
return new Integer((o1 == null) ? 0 : o1.size()).compareTo((o2 == null) ? 0 : o2.size());
}
};
public static void main(String[] args) {
// LinkedList<LinkedList<Long>>() overalllList = new LinkedList<LinkedList<Long>();
// Note there is an extra () to the left of your overalllList.
LinkedList<LinkedList<Long>> overalllList = new LinkedList<LinkedList<Long>>();
LinkedList<Long> list3 = new LinkedList<Long>();
LinkedList<Long> list2 = new LinkedList<Long>();
LinkedList<Long> list1 = new LinkedList<Long>();
for (long i = 0; i < 5; i++) { // 5, or 1000
if (i < 2) {
list1.add(i);
}
if (i < 3) { // 3, or 245.
list2.add(i);
}
list3.add(i);
}
overalllList.add(list3);
overalllList.add(list2);
overalllList.add(list1);
System.out.println("Before: " + overalllList);
Collections.sort(overalllList, comp);
System.out.println("After: " + overalllList);
}
Output is 输出是
Before: [[0, 1, 2, 3, 4], [0, 1, 2], [0, 1]]
After: [[0, 1], [0, 1, 2], [0, 1, 2, 3, 4]]
List<List<Long>> overalllList = new LinkedList<List<Long>>();
overalllList.add(Arrays.asList(1L, 2L, 3L));
overalllList.add(Arrays.asList(4L, 5L, 6L, 7L, 8L));
overalllList.add(Arrays.asList(9L));
Collections.sort(overalllList, new Comparator<List<Long>>() {
@Override
public int compare(List<Long> list1, List<Long> list2) {
return list1.size() - list2.size();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.