How to sort a list of lists according to the first element of each list?

Viewed 39

For example, giving this unsorted list:

[[1,4,7],[3,6,9],[2,59,8]]

The sorted result should be:

[[1,4,7],[2,59,8],[3,6,9]]

2 Answers
List<List<Integer>> list = ...
list.sort(Comparator.comparing(l -> l.get(0));

Suppose each elememnt in your lists have at least one element,then you can try following code

    List<List<Integer>> lists = new ArrayList<>();
    lists.add(Arrays.asList(1, 4, 7));
    lists.add(Arrays.asList(3, 6, 9));
    lists.add(Arrays.asList(2, 59, 8));
    System.out.println(lists);
    Collections.sort(lists, (a, b) -> a.get(0).compareTo(b.get(0)));
    System.out.println(lists);
Related