问题描述
我很难找到通过 ArrayList
中的第三个元素对 ArrayList
进行排序的方法.例如,给定
I'm having difficulty finding a way to sort an ArrayList<ArrayList<Integer>>
by the third element in the ArrayList<Integer>
. For example, given
ArrayList
我想对其进行排序,以便 ArrayList
按给出输出的第三个元素按升序排列:
I want to sort it so that the ArrayList<Integer>
s are in ascending order by the third element giving the output:
ArrayList
我之前使用过 Collections
对 ArrayList 进行排序,但这个有点棘手.
I have utilized Collections
in sorting an ArrayList before but this one is a bit trickier.
下面的 java 代码也可能有助于理解我遇到的问题.
The java code below may also help with understanding the problem I am having.
public static void main(String[] args){
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
Random rand = new Random();
for(int i=0; i<3; i++){
ArrayList<Integer> components = new ArrayList<Integer>();
components.addAll(Arrays.asList(rand.nextInt(10),rand.nextInt(10),rand.nextInt(10)));
list.add(components);
}
System.out.println(list);
sort(list);
}
public static void sort(ArrayList<ArrayList<Integer>> list){
for(int i=0; i<list.size(); i++){
//Here is where I want to sort the list by the element retrieved from the println below
System.out.println(list.get(i).get(2));
}
}
感谢任何帮助.感谢您抽出宝贵时间.
Any help is appreciated. Thanks for your time.
推荐答案
您可以使用 Arrays.asList
来构建您的 List
(请程序到接口)并假设您使用的是 Java 8+,您可以使用 lambda 编写一个 Comparator
.喜欢,
You might use Arrays.asList
to construct your List<List<Integer>>
(please program to the interface) and assuming you are using Java 8+, you can write a Comparator
with a lambda. Like,
public static void main(String[] args) {
List<List<Integer>> al = Arrays.asList( //
Arrays.asList(5, 4, 0), Arrays.asList(3, 2, 1), //
Arrays.asList(3, 3, 3), Arrays.asList(2, 2, 2));
Collections.sort(al, (a, b) -> a.get(2).compareTo(b.get(2)));
// Collections.sort(al, (a, b) -> Integer.compare(a.get(2), b.get(2)));
System.out.println(al);
}
哪些输出
[[5, 4, 0], [3, 2, 1], [2, 2, 2], [3, 3, 3]]
这篇关于对 ArrayList<ArrayList<Integer>> 进行排序通过 ArrayList<Integer> 中的第三个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!