3

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;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Luisa Hernández
  • 596
  • 1
  • 3
  • 17
  • 1
    If possible, you should use Guava's [Multimap](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html) which does exactly what you try to achieve. The advice on implementing equals still stands using Multimap. – wonderb0lt Apr 29 '15 at 15:03

2 Answers2

3

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

Community
  • 1
  • 1
Arnaud Potier
  • 1,750
  • 16
  • 28
1

Your class API, should implement Interface Comparable so that your Set will be able to check whether 2 API are equals or not.

yahya el fakir
  • 562
  • 2
  • 12