How to remove duplicate Key-Value pair in Hashmap? - Not only duplicate key or value

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

[SoftwareID, SoftwareAPI]

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

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

But I have a problem, I need to remove all duplicate SoftwareAPIs for each software.

For example, when I iterate over my hash file, 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 duplicate 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 information about the codes, this is a piece 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;
}

      

+3


source to share


2 answers


From java Install add documentation method :

adds the specified element e to this set if the set does not have an element e2 such that (e == null? e2 == null: e.equals (e2))

When you add your items to your set, they probably don't count as equal.

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



This is very easy to do in TDD.

hashCode is used when using HashSet (this is your case).

Also see this question about hashSet and equals methods

+3


source


The API of your class must implement the Comparable interface so that your Set can check if 2 APIs are equal or not.



+1


source







All Articles