0

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.

4
  • 1
    are the third elements unique? or they may get repeated? Commented Jul 30, 2017 at 5:55
  • they are not unique, and there may be multiple ones Commented Jul 30, 2017 at 5:56
  • 3
    list.sort(Comparator.comparing(l -> l.get(2))); Commented Jul 30, 2017 at 6:04
  • thank you shmosel works as intended Commented Jul 30, 2017 at 6:21

1 Answer 1

3

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

but can you explain how it works based on third element?
@Salman In the lambda expression (a, b) -> Integer.compare(a.get(2), b.get(2)) we are comparing the third element of a with the third element of b (the first is 0, the second is 1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.