Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get minvalue of a Map(Key,Double)

Tags:

java

guava

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 according to the values, and take the first/last one.

like image 603
user326667 Avatar asked May 05 '10 19:05

user326667


People also ask

How do I get the value of a map for a specific key?

HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can 2 keys have same value in map?

However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.

Can a map hold duplicate keys?

The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.

Can HashMap have two keys?

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.


2 Answers

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

Map<String, Double> map = new HashMap<String, Double>(); 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<String, Double> min = null; for (Entry<String, Double> entry : map.entrySet()) {     if (min == null || min.getValue() > entry.getValue()) {         min = entry;     } }  System.out.println(min.getKey()); // 0.1 

(nullcheck on min left aside)

like image 155
BalusC Avatar answered Sep 20 '22 01:09

BalusC


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

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

With Java 8:

Entry<String, Double> min = Collections.min(map.entrySet(),                                        Comparator.comparing(Entry::getValue)); 
like image 41
superfav Avatar answered Sep 22 '22 01:09

superfav