Get minvalue of a Map(Key,Double)

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

    In Java 8 we can get easily:

    Double minValue = map.entrySet().stream().min(Map.Entry.comparingByValue()).get().getValue();
    Double maxValue = map.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
    
    0 讨论(0)
  • 2020-12-05 07:46

    I'd be inclined to use a Google Collections BiMap:

         String minKey = HashBiMap.create(map).inverse().get(Collections.min(map.values()));
    

    Or something like that (not tested).

    0 讨论(0)
  • 2020-12-05 07:46

    Using java 8 (and static imports). We can make @superfav's solution much tidier:

    Map<String, Double> myMap;
    String theKeyWithHighestValue = Collections.min(myMap.entrySet(), comparingDouble(Entry::getValue)).getKey()
    
    0 讨论(0)
  • 2020-12-05 07:47

    In order to do it efficiently, you may want to define your own data structure, such that it implements the Map interface,but also allows efficient getMin() operation.

    This can be done using two internal data structures: a map and a tree (or heap data structure). Each time a new pair (K,V) is added, add them to the map, and also to the tree (as a single entry). This allows O(1) time for get(Key) operations, and O(log n) time for addition, removal, and getMin operations.

    0 讨论(0)
  • 2020-12-05 07:53

    Java8 One-Liner

    Key key = Collections.min(map.entrySet(), Map.Entry.comparingByValue()).getKey()
    
    0 讨论(0)
  • 2020-12-05 07:58

    Using Java 8 streams:

    return map
                .entrySet()
                .stream()
                .sorted(Comparator.comparingDouble(Map.Entry::getValue))
                .findFirst()
                .map(Map.Entry::getValue);
    

    Or

    return map
                .entrySet()
                .stream()
                .min(Comparator.comparingDouble(Map.Entry::getValue))
                .map(Map.Entry::getValue);
    

    But if you want to do it multiple times, then definitely give heap a look.

    0 讨论(0)
提交回复
热议问题