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

Time:03-28

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

[5, 10]

[2, 11]

[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.

CodePudding user response:

With Stream API (Java 8):

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));

    System.out.println("sorted asc = "   list.stream()
            .sorted(Comparator.comparing(o -> o.get(0)))
            .collect(Collectors.toList()));

    System.out.println("sorted desc = "    list.stream()
            .sorted((i, j) -> -i.get(0).compareTo(j.get(0)))
            .collect(Collectors.toList()));
}

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

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

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

CodePudding user response:

You could use Comparator.comparingInt:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> lists =
            new ArrayList<>(
                List.of(
                    new ArrayList<>(List.of(5, 10)),
                    new ArrayList<>(List.of(2, 11)),
                    new ArrayList<>(List.of(1, 12)),
                    new ArrayList<>(List.of(8, 13))
                ));
        System.out.println("Sorted ascending based on first element:");
        lists.sort(Comparator.comparingInt(l -> l.get(0)));
        System.out.println(lists);
        System.out.println("Sorted descending based on first element:");
        lists.sort(Comparator.comparingInt(l -> -l.get(0)));
        System.out.println(lists);
    }
}

Output:

Sorted ascending based on first element:
[[1, 12], [2, 11], [5, 10], [8, 13]]
Sorted descending based on first element:
[[8, 13], [5, 10], [2, 11], [1, 12]]
  • Related