Get minvalue of a Map(Key,Double)

前端 未结 9 1950
一个人的身影
一个人的身影 2020-12-05 07:08

Is there a method (maybe with Google Collections) to obtain the min value of a Map(Key, Double)?

In the traditional way, I would have to sort the map ac

9条回答
  •  一生所求
    2020-12-05 08:01

    You still can use Collections.min with a custom Comparator to get the Map.Entry with the lower value:

    Map map = new HashMap();
    map.put("1.1", 1.1);
    map.put("0.1", 0.1);
    map.put("2.1", 2.1);
    Entry min = Collections.min(map.entrySet(), new Comparator>() {
        public int compare(Entry entry1, Entry entry2) {
            return entry1.getValue().compareTo(entry2.getValue());
        }
    });
    System.out.printf("%s: %f", min.getKey(), min.getValue()); // 0.1: 0.100000
    

    With Java 8:

    Entry min = Collections.min(map.entrySet(),
                                           Comparator.comparing(Entry::getValue));
    

提交回复
热议问题