[英]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中根据full_inc从高到低对这个地图列表进行排序
您可以在下面给出的 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
.您可以使用自定义比较器,但您需要您的值(当前为
Object
)来实现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我会
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.解决方案 1 是将要排序的所有条目放在
TreeMap<K,V>
(TreeMap doc ) 中,其中 K 是您排序的条件(此处为 full_inc),而 V 是您要排序的内容。 Then TreeMap.entrySet will be iterated following the compare() order of your K
.然后 TreeMap.entrySet 将按照
K
的 compare() 顺序进行迭代。
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.解决方案 2 是使用 full_inc 创建您自己的Comparable类以与同一类的对象进行比较,并使用Collections.sort与它。
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()
解决方案 3 几乎与 2 相同,使用Collections.sort和比较器根据它们的
getFullInc()
比较自定义类的两个实例
您可以将 Collections.sort() 与您自己的比较器一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.