0

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

reggaemuffin
  • 1,188
  • 2
  • 11
  • 26
Deepak Kumar
  • 2,317
  • 5
  • 23
  • 21

5 Answers5

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())));
vikash
  • 381
  • 2
  • 11
3

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

I would

  • Make your maps object of a custom class.
  • Make your custom class implement Comparable
  • Use Collections.sort()
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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

jolivier
  • 7,380
  • 3
  • 29
  • 47
0

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

barak1412
  • 972
  • 7
  • 17