【问题标题】:Java sort LinkedList of LinkedLists into size orderJava将LinkedLists的LinkedList排序为大小顺序
【发布时间】:2014-03-19 17:22:03
【问题描述】:

我目前面临这个问题:我有一个 LinkedList,其中包含多个包含 long 的 LinkedList,所以:

LinkedList<LinkedList<Long>>() overalllList = new LinkedList<LinkedList<Long>();

在一些代码运行后,整个 List 被各种大小的 long 列表填充。我需要做的是对整体列表进行排序,以便它包含从最小到最大的长列表。

我希望这是有道理的。

为了澄清,我需要这个:

OverallList:
    LinkedList<Long> (size 2) - first
    LinkedList<Long> (size 245) - second
    LinkedList<Long> (size 1000) - third
    ...etc

我不确定使用 Collections 是否可以做到这一点,或者我是否需要查看自定义比较器。任何意见或建议将不胜感激。

谢谢

【问题讨论】:

  • 是的,您需要自定义Comparator
  • 您需要考虑到您的列表将包含可变元素。所以它可能不会一次订购。
  • 谢谢你告诉我,我现在去看看。

标签: java list collections comparator


【解决方案1】:

这是一种方法的示例,

// 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);
}

输出是

Before: [[0, 1, 2, 3, 4], [0, 1, 2], [0, 1]]
After: [[0, 1], [0, 1, 2], [0, 1, 2, 3, 4]]

【讨论】:

  • 谢谢 Elliott,我会试试看的!
【解决方案2】:
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();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-09-28
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多