排序列表< Map< String,Object>>基于价值 [英] Sort List<Map<String,Object>> based on value

查看:62
本文介绍了排序列表< Map< String,Object>>基于价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个 List< Map< String,Object>> ,我想按地图中某些键的值对它进行排序.

Basically I have a List<Map<String,Object>>, and I want to sort it by the values of certain key in the map.

问题是我不知道类型...此映射可以包含字符串,整数,双精度数,浮点数等....我想对它进行排序:

The problem is that I do not know the type... This map can contain Strings, Integers, Doubles, Floats etc.... I would like to sort it:

到目前为止

List<Map<String,Object>> data = getResults();
Collections.sort(data, (o1, o2) -> (String.valueOf(o2.get("Field1")))
              .compareTo((String.valueOf(o1.get("Field1")))));

这不是一个好主意,因为数字没有正确排序....我该如何处理?

It is not a great Idea since numbers are not properly sorted.... How can I handle this?

推荐答案

您可以归纳通过比较其双精度值来比较数字,因为他们是最大的.如果无法将两个对象强制转换为 numbers ,并且无法从这些对象解析 double值,则比较它们的 string值 :

You can generalize comparing numbers by comparing their double values, because they are the largest. If two objects cannot be cast to numbers and the double value cannot be parsed from these objects, then compare their string values:

List<Map<String, Object>> data = Arrays.asList(
        Map.of("Field1", 21.2d),  // Double
        Map.of("Field1", "qqq"),  // String
        Map.of("Field1", "22.5"), // String
        Map.of("Field1", 2),      // Integer
        Map.of("Field1", 3L),     // Long
        Map.of("Field1", 23.1f)); // Float

data.sort(Comparator.comparingDouble((Map<String, Object> map) -> {
    Object object = map.get("Field1");
    if (object instanceof Number) {
        return ((Number) object).doubleValue();
    } else {
        try {
            return Double.parseDouble(String.valueOf(object));
        } catch (NumberFormatException e) {
            return Double.NaN;
        }
    }
}).thenComparing(map -> String.valueOf(map.get("Field1"))));

data.forEach(System.out::println);
// {Field1=2}
// {Field1=3}
// {Field1=21.2}
// {Field1=22.5}
// {Field1=23.1}
// {Field1=qqq}


另请参见:按列标题对2D列表进行排序

这篇关于排序列表&lt; Map&lt; String,Object&gt;&gt;基于价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆