Search code examples
javahashmapduplicateshashset

How to remove duplicate Key-Value pair in Hashmap ? - Not just duplicate Key or Value


I have a hashmap in Java for retrieving APIs of software system. So, I have something like this:

[SoftwareID, SoftwareAPI] 

When I ask for all APIs for software systems, I get:

[ [SoftwareID, SoftwareAPI], [SoftwareID, SoftwareAPI], [SoftwareID, SoftwareAPI] ]

But I have a problem, I need to remove all duplicates SoftwareAPIs per software.

For example when I iterate over my hashmap I get,

[ [0, A], [0, B], [0, A], [0, A] ];

[ [1, A], [1, B], [1, B], [1, C] ];

[ [2, A], [2, B], [2, A] ];

but I need to remove duplicated pairs, so it would be something like this:

[ [0, A], [0, B] ];

[ [1, A], [1, B], [1, C] ];

[ [2, A], [2, B] ]

Just to add some code information here is part of code:

// HashMap APIs per user/Systems
HashMap<Integer, Set<API>> apisPerSystem = new HashMap<Integer, Set<API>>();

/**
 * Stores a API in the data model
 * @param system the user
 * @param api the item
 * @return the newly added API
 */
public API addAPIs(int system, String api) {
    API r = new API(system,api);
    apis.add(r);
    Set<API> systemApis = apisPerUser.get(system);
    if (systemApis == null) {
        systemApis = new HashSet<API>();
    }
    apisPerUser.put(system, systemApis);
    systemApis.add(r);
    systems.add(system);
    apisList.add(api);
    return r;
}

// Get the APIs per Systemfrom the outside.
public HashMap<Integer, Set<API>> getAPIsPerSystem() {
    return apisPerSystem;
}

Solution

  • From java's Set method add documentation:

    adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2))

    When you add your elements to your set, they are probably not considered equal.

    You probably need to check the hashCode and equals method of your API object, and override them.

    This is very easily done in TDD.

    hashCode is used when using a HashSet (which is your case).

    Also see this question about hashSet and equals methods