user1015388
user1015388

Reputation: 1515

How to sort List<Object> in Java 8

I have a List of object where the Object type is just java.lang.Object.

List<Object> lst = new ArrayList();

lst has value:

[
["abc", "987", "er"],
["abcdefgh", "229", "df"],
["pqrs", "539", "ab"],
]

I want to list to be sorted on the Objects's second property value. The list should be,

[
["abcdefgh", "229", "df"],
["pqrs", "539", "ab"],
["abc", "987", "er"]
]

Upvotes: 0

Views: 3222

Answers (3)

i.bondarenko
i.bondarenko

Reputation: 3572

Lets assume List<Object> == List<List<Comarable>>. So we can do it in this way:

public static void main(String[] args) {
    List<List<Comarable>> lst = new ArrayList(Arrays.asList(
            Arrays.asList("abc", 987, "er"),
            Arrays.asList("abcdefgh", 229, "df"),
            Arrays.asList("pqrs", 539, "ab")));
    List<List<String>> sorted = lst.stream()
            .sorted(Comparator.comparing(l -> l.get(1)))
            .collect(Collectors.toList());
    System.out.println("Original: " + lst);
    System.out.println("Sorted: " + sorted);
}

Output:

Original: [[abc, 987, er], [abcdefgh, 229, df], [pqrs, 539, ab]]

Sorted: [[abcdefgh, 229, df], [pqrs, 539, ab], [abc, 987, er]]

Upvotes: 0

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

You can write a custom Comparator. For instance, you can parse the 2nd element of each List to Integer and then compare on the basis of that:

// Some dummy data
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("abc", "1987", "er"));
list.add(Arrays.asList("abcdefgh", "229", "df"));
list.add(Arrays.asList("pqrs", "539", "ab"));

// Sorting using custom Comparator
list.sort(Comparator.comparing(x -> Integer.parseInt((String) ((List) x).get(1))));

// Printing
System.out.println(list);

Output:

[["abcdefgh", "229", "df"], ["pqrs", "539", "ab"], ["abc", "1987", "er"]]

But this method is not the best way. You should be having a DTO class for that and you should map this JSON to your DTO class. And then perform transformation on that data.

Upvotes: 0

duffymo
duffymo

Reputation: 308743

You can write a custom comparable, but this is a poor abstraction.

If you're using JSON, why hide the fact by creating a List<Object>?

I'd recommend using a library like Jackson to manage your JSON and do your sorting on that.

Upvotes: 1

Related Questions