简体   繁体   中英

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM