HashMap: How to obtain the element with the highest value?.
You can use this method, which compares the value of each entry to obtain the maximum value:
public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){
Entry<String, Integer> maxEntry = null;
Integer max = Collections.max(map.values());
for(Entry<String, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
if(null != value && max == value) {
maxEntry = entry;
}
}
return maxEntry;
}
as an example assuming this HashMap
:
HashMap map = new HashMap<String, Integer>() {
{
put("toyota", 1);
put("nissan", 5);
put("mazda", 3);
put("bmw", 4);
put("kia", 2);
put("dacia", 0);
}
};
The Entry with maximum value would be
("nissan", 5)
which can be obtained by calling the method in this way:
Map.Entry<String, Integer> maxEntry = getMaxEntry(map);
With Java 8 you can get it this way:
Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("maxEntry = " + maxEntry);
you will have the result:
nissan
How to order values in a HashMap?
It can be done using this method:
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map ){
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<K, V>>(){
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2){
return (o1.getValue()).compareTo( o2.getValue() );
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list){
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
The previous method can be called in this way, obtaining the ordered values, as an example the following HashMap
:
HashMap map = new HashMap<String, Integer>() {
{
put("toyota", 1);
put("nissan", 5);
put("mazda", 3);
put("bmw", 4);
put("kia", 2);
put("dacia", 0);
}
};
We call the method to obtain a Map with the ordered values:
Map valoreOrdenados = sortByValue(map);
You can iterate to see the result:
Iterator it = valoreOrdenados.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
System.out.println(entry.getKey() + " => " + entry.getValue());
it.remove(); // evita ConcurrentModificationException =)
}
resulting in
dacia => 0
toyota => 1
kia => 2
mazda => 3
bmw => 4
nissan => 5