Madhu
Madhu

Reputation: 5766

Sorting List<Map<String, Object>>

I am having the below object

List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();

How do i sort this based on the value ("Object") in the Map?

Upvotes: 4

Views: 4759

Answers (3)

vikash
vikash

Reputation: 455

One of the easiest ways to solve using Java 8 is :

Collections.sort(listMap, Comparator.comparing(map -> (String)map.get("key")));

Or,

listMap = listMap.stream().sorted(Comparator.comparing(map -> (String)map.get("key"))).collect(Collectors.toList());

Note: I have converted key(Object) into String. You can use as per your requirements.

Upvotes: 1

Luixv
Luixv

Reputation: 8710

Use your own Comparator (You have to implement the given interface)

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240900

Create your own Comparator and use it .

List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
Collections.sort(listMap,new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                //your logic goes here
            }
});

Upvotes: 8

Related Questions