S.Else S.Else - 5 months ago 24
Java Question

Handling duplicate values in HashMaps

I have a populated hashmap in the form

Hashmap<String , ArrayList<Double>>
. There are many cases in which the values (Arraylist) are the same. What I want tro do is if the value is same , the two separate entries should be changed to one with a change in the key. For eg:

HashMap<String, ArrayList<Double>> map = new HashMap<>();
ArrayList<Double> arr = new ArrayList<>();
arr.add(1);
arr.add(2)
map.put("a",arr);
map.put("b",arr);
map.put("c",arr);


This should result in a hashmap with a single entry :

{a, b , c=[1,2]}


I have tried to solve this for hours but am still unable to do so. A million thanks in advance.

Answer

Creating your custom HashMap and overriding put() should work, it is not really efficient though.

Something like this:

public class CustomMap extends HashMap<String, ArrayList<Double>> {
    @Override
    public ArrayList<Double> put(String key, ArrayList<Double> value) {
        String oldKey = "";

        for (Entry<String, ArrayList<Double>> entry : entrySet()) {
            if (entry.getValue().equals(value)) {
                oldKey = entry.getKey();
                remove(entry.getKey());
            }
        }
        // combine your keys as you wish
        String newKey = oldKey + key;
        return super.put(newKey, value);
    }
}

To use it, just replace the following:

HashMap<String, ArrayList<Double>> map = new HashMap<>();

With:

CustomMap map = new CustomMap();
Comments