S.Else S.Else - 3 months ago 8x
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<>();

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.


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>> {
    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();
        // 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<>();


CustomMap map = new CustomMap();