Home > Software engineering >  Sorting arraylist of array list
Sorting arraylist of array list

Time:03-20

I waned to sort an array list of arraylist of numbers using java, so basically if I have the following arraylist:

arr.add(<1,0>)
arr.add(<0,3>)
arr.add(<2,1>)
arr.add(<2,2>)

the output should be:

<0,3>
<1,0>
<2,1>
<2,2>

The arraylist should be sorted according to the first key then the second key.

CodePudding user response:

Here is one way. Use lists.sort()

The data

List<List<Integer>> lists =
        new ArrayList<>(List.of(List.of(0, 3), List.of(1, 0),
                List.of(2, 1), List.of(2, 2)));

Shuffle for demo

Collections.shuffle(lists);
  • First compare the first element of each list and sort normally
  • If two elements are equal, then sort based on the next element.
lists.sort(Comparator
        .comparing((List<Integer> lst) -> lst.get(0))
        .thenComparing(lst -> lst.get(1)));

lists.forEach(System.out::println);

prints

[0, 3]
[1, 0]
[2, 1]
[2, 2]
  • Related