Sort List> based on value

后端 未结 2 686
我在风中等你
我在风中等你 2021-01-16 05:10

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

The problem is that I do not know

2条回答
  •  耶瑟儿~
    2021-01-16 05:12

    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> 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 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}
    

    See also: Sort 2D List by Column Header

提交回复
热议问题