Simple java8 solution for map Map<Object,Integer> map = new HashMap<>();
map.values().stream().min(Integer::compare).get();
Edit
As @Andreas pointed out, there was request for using comparator, so this is solution for Java 8 which finds smallest value
public static <K, V> V min8(Map<K, V> map, Comparator<V> comp) {
return map.values().stream().min(comp).get();
}
and this is solution for Java 7 for finding entry with smallest value
public static <K, V> Entry<K, V> min(Map<K, V> map, Comparator<V> comp) {
Iterator<Entry<K, V>> entries = map.entrySet().iterator();
if (!entries.hasNext()) {
return null;
}
Entry<K, V> min;
for (min = entries.next(); entries.hasNext();) {
Entry<K, V> value = entries.next();
if (comp.compare(value.getValue(), min.getValue()) < 0) {
min = value;
}
}
return min;
}
my initial solution was very close to @Andreas, so i decide to change and use for loop with itterator.