简体   繁体   中英

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

您可以在下面给出的 Java 8 中使用:

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

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.

I would

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

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

您可以将 Collections.sort() 与您自己的比较器一起使用。

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