我遇到了以下问题。我有一个ArrayList(1)的ArrayLists(2)。我需要做的是,对结构进行排序,使ArrayLists(2)的第一个元素按升序下降ArrayList(1)。澄清:
输入:
3, 8, 6
2, 14, 205, 44, 1
1, 3
输出:
1, 3
2, 14, 205, 44, 1
3, 8, 6
看看它如何仅根据第一个值对行进行排序。
现在,我定义数组列表的方式是:
List<List<Integer>> graph = new ArrayList<List<Integer>>();
// and I add elements to it likewise
graph.get(currentIndex).add(new ArrayList<Integer>());
我之所以使用ArrayList,是因为我读到了它比LinkedList更有效的内存,还因为我正在构建一个图的邻接列表。在它中,每个节点的节点数或邻接列表的长度都可以改变。行的第一个元素是start_node
,下面是它的相邻元素。你能告诉我怎样才能实现这种分类吗?
发布于 2018-10-23 19:49:05
因此,据我所知,您希望按照每个嵌套列表的第一个元素对顶级列表进行排序。这是正确的吗?下面是我要做的事情:
List<List<Integer>> graph = new ArrayList<List<Integer>>();
// add a bunch of things ...
// ...
// Now, to sort:
graph.sort((x,y) -> Integer.compare(x.get(0), y.get(0)));
这是使用Integer
获取一个Comparator
,这是sort()
方法根据某些自定义条件进行排序所需要的。在本例中,我们告诉它对List
of Lists
graph
进行排序,方法是比较graph
中的两个任意项,获取它们的第一个项,并按照通常比较Integer
的项进行比较。
请注意,这假设graph
中的所有项都有第一项。
发布于 2018-10-23 19:44:46
要比较两个子列表,您需要找到第一个非相等对,并比较它们的值(如果两者都以类似的32
开头,则需要查找下一个值来查看)。
List<List<Integer>> graph = new ArrayList<>();
graph.add(Arrays.asList(3, 8, 6));
graph.add(Arrays.asList(2, 14, 205, 44, 1));
graph.add(Arrays.asList(2, 14, 205, 44, 2));
graph.add(Arrays.asList(1, 3));
graph.add(Arrays.asList(1, 4));
graph.add(Arrays.asList(1, 4));
graph.add(Arrays.asList(1, 4, 5));
graph.sort((o1, o2) -> {
int indice, cmp, min;
for (indice = 0, min = Math.min(o1.size(), o2.size());
indice < min; indice++) {
if ((cmp = Integer.compare(o1.get(indice), o2.get(indice))) != 0) {
return cmp;
}
}
if (indice == o1.size()) return -1;
if (indice == o2.size()) return 1;
return 0;
});
System.out.println(graph);
[[1, 3],
[1, 4],
[1, 4],
[1, 4, 5],
[2, 14, 205, 44, 1],
[2, 14, 205, 44, 2],
[3, 8, 6]]
另外,另一种使用Comparator
接口的方法(我同意这不是很好),它比较值,直到列表中的一个如果为空,那么它将比较大小,如果它完全达到一个。
graph.sort((o1, o2) -> {
Comparator<List<Integer>> cc = Comparator.comparingInt(l -> l.get(0));
int indice, min;
for (indice = 0, min = Math.min(o1.size(), o2.size()); indice < min; indice++) {
final int i = indice;
cc = cc.thenComparingInt(l -> l.get(i));
}
return cc.thenComparingInt(List::size).compare(o1, o2);
});
发布于 2018-10-24 10:10:49
这是我想出的另一个解决方案。
其思想是:使用Collection的静态方法sort(),并将其与对list的引用以及由compare()定义的新的比较器对象一起输入。
Collections.sort(graph, new Comparator<List<Integer>>(){
@Override
public int compare(List<Integer> aList1, List<Integer> aList2) {
return aList1.get(0).compareTo(aList2.get(0));
}
}));
https://stackoverflow.com/questions/52956573
复制相似问题