Jamin
Jamin

Reputation: 1402

Sorting an ArrayList<ArrayList<Integer>> by the third element in the ArrayList<Integer>

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.

Upvotes: 0

Views: 232

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

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

Which outputs

[[5, 4, 0], [3, 2, 1], [2, 2, 2], [3, 3, 3]]

Upvotes: 3

Related Questions