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

How to sort an ArrayList of ArrayLists (by one of the variables) in Java?

(Java 8) I have an ArrayList of ArrayLists as follows:

[5, 10]

[2, 11]

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

[1, 12]

[8, 13]

I want these lists to be sorted by the first value in the list in either ascending or descending order. For example, with ascending order, the ArrayList would be ordered as:

[1, 12]

[2, 11]

[5, 10]

[8, 13]

How can I do this?

I am struggling with using the comparator class. Other documentation I have seen refers to when this data is represented by an array, (Arrays.sort then defining a comparator in the argument), but when it is a List of ArrayLists I cannot figure out the solution.

>Solution :

With a stream:

public static void main(String[] args) {
    List<List<Integer>> list = new ArrayList<>();

    list.add(asList(5, 10));
    list.add(asList(2, 11));
    list.add(asList(1, 12));
    list.add(asList(8, 15));

    List<List<Integer>> sorted = list.stream()
            .sorted(Comparator.comparing(o -> o.get(0)))
            .collect(Collectors.toList());

    System.out.println("sorted = " + sorted);
}

private static List<Integer> asList(Integer... arr) {
    return Arrays.asList(arr);
}

sorted = [[1, 12], [2, 11], [5, 10], [8, 15]]

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