Deepak Kumar
Deepak Kumar

Reputation: 2457

How to i sort a List<Map<String,Object>> in java

I am getting

  List<Map<String,Object>> listMap = [
    {employee=17, fromdate=2010-08-01 00:00:00.0, full_inc=25572.0000},
    {employee=17, fromdate=2010-09-01 00:00:00.0, full_inc=28347.0000},  
    {employee=17, fromdate=2010-10-01 00:00:00.0, full_inc=37471.0000},
    {employee=17, fromdate=2011-02-01 00:00:00.0, full_inc=47033.0000},
    {employee=17, fromdate=2011-07-01 00:00:00.0, full_inc=50592.0000}
  ]

can anyone help me how do i sort this list of map based on full_inc from high amount to low amount in java

Upvotes: 0

Views: 12085

Answers (5)

You can use in Java 8 which is given below :

listMap.sort(Comparator.comparing(m->(double) m.get("full_inc"),Comparator.nullsLast(Comparator.reverseOrder())));

Upvotes: 5

barak1412
barak1412

Reputation: 1160

You can use Collections.sort() with your own comparator.

Upvotes: 0

jolivier
jolivier

Reputation: 7655

Solution 1 is to put all entries you want to sort in a TreeMap<K,V>(TreeMap doc) where K is you criteria on which you sort (here full_inc) and V is what you want to sort. Then TreeMap.entrySet will be iterated following the compare() order of your K.

Solution 2 is to create your own Comparable class using full_inc to compare with objects of the same class and use Collections.sort with it.

Solution 3 is almost the same as 2, using Collections.sort with a comparator comparing two instance of your custom class based on their getFullInc()

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533880

I would

  • Make your maps object of a custom class.
  • Make your custom class implement Comparable
  • Use Collections.sort()

Upvotes: 1

assylias
assylias

Reputation: 328923

You can use a custom comparator, but you need your values (currently Object) to implement Comparable. Based on the current declaration of your list, you can't do it (how do you compare two random objects?):

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

    @Override
    public int compare(Map<String, Comparable> m1, Map<String, Comparable> m2) {
        return m2.get("full_inc").compareTo(m1.get("full_inc")); //descending
    }
});

Note: you need to add error checking.

Upvotes: 3

Related Questions