OK, I have
Set<String> s;
HashMap<String, Double> hm;
And, I want to find keys in hm
which are related to the maximum values among all possible key(candidate)s in the set s.
Below method is what I already have, which helps me to find multiple keys regarding to one values. I might use Collections.Max(hm.values())
to get the maximum value
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
What would be the 'neat' solution that you can suggest?
I was working with Python for past few months, and now it is so inconvenient to deal with all sort of Maps instead of dictionaries by Java.
What I want to remark on this question is, simplifying below code in somewhat 'smarter' way in Java.
import com.google.common.collect.Sets;
double maxVal = 0.0;
for(String candidate : s){
if(hm.get(candidate) >= maxVal){
maxVal = hm.get(candidate);
}
}
Set<String> subset = Sets.intersection(set, getKeysByValue(hm, maxVal));
Possible Python-like implementation (List comprehension) is
subset = set.intersection(s, getKeysByValue(hm, Collections.max([hm.get(item) for item in s]))