Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting arraylist of array list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading