简体   繁体   中英

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"]
]

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.

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]]

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.

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