Get minvalue of a Map(Key,Double)

前端 未结 9 1943
一个人的身影
一个人的身影 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:02

    You can use the standard Collections#min() for this.

    Map map = new HashMap();
    map.put("1.1", 1.1);
    map.put("0.1", 0.1);
    map.put("2.1", 2.1);
    
    Double min = Collections.min(map.values());
    System.out.println(min); // 0.1
    

    Update: since you need the key as well, well, I don't see ways in Collections or Google Collections2 API since a Map is not a Collection. The Maps#filterEntries() is also not really useful, since you only know the actual result at end of iteration.

    Most straightforward solution would then be this:

    Entry min = null;
    for (Entry entry : map.entrySet()) {
        if (min == null || min.getValue() > entry.getValue()) {
            min = entry;
        }
    }
    
    System.out.println(min.getKey()); // 0.1
    

    (nullcheck on min left aside)

提交回复
热议问题