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<Integer>> = [[5,4,0],[3,2,1],[3,3,3],[2,2,2]]
I want to sort it so that the ArrayList<Integer>s are in ascending order by the third element giving the output:
ArrayList<ArrayList<Integer>> = [[5,4,0],[3,2,1],[2,2,2],[3,3,3]]
I have utilized Collections in sorting an ArrayList before but this one is a bit trickier.
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.
list.sort(Comparator.comparing(l -> l.get(2)));