Answer the question
In order to leave comments, you need to log in
How to write in Map the maximum value for each of the keys?
Comrades, tell me!
By default, Map is set to the last added value for a given key. How to write the maximum value for each of the keys?
Map<String, Integer> maps = new HashMap<String, Integer>();
maps.put("A", 5);
maps.put("B", 2);
maps.put("A", 8);
maps.put("B", 7);
maps.put("A", 3);
maps.put("B", 3);
A = 8
B = 7
Answer the question
In order to leave comments, you need to log in
Just write your insert implementation:
public class MyCustomMap extends HashMap<String, Integer> {
@Override
public Integer put(String key, Integer value) {
Integer oldValue = get(key);
if (oldValue == null || oldValue < value) {
return super.put(key, value);
}
return null;
}
}
Map<String, Integer> maps = new MyCustomMap();
maps.put("A", 5);
maps.put("B", 2);
maps.put("A", 8);
maps.put("B", 7);
maps.put("A", 3);
maps.put("B", 3);
System.out.println(maps.get("A"));
System.out.println(maps.get("B"));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question