P
P
PunKHS2015-12-27 16:22:17
Java
PunKHS, 2015-12-27 16:22:17

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);

It should turn out:
A = 8
B = 7

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur, 2015-12-27
@PunKHS

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"));

G
GavriKos, 2015-12-27
@GavriKos

Make your put method. You check in it, if there is no such key, enter it immediately into the map. If there is - compare where more - in the map or what is entered. If what is brought in, bring it in. If in the map - do nothing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question