如何删除 Hashmap 中重复的键值对? - 不只是复​​制键或值

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

我在 Java 中有一个 hashmap 用于检索软件系统的 API。所以,我有这样的东西:

[SoftwareID, SoftwareAPI] 

当我请求软件系统的所有 API 时,我得到:

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

但是我有一个问题,我需要删除每个软件的所有重复软件 API。

例如,当我遍历我的 hashmap 时,我得到,

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

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

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

但我需要删除重复的对,所以它会是这样的:

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

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

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

这里补充一些代码信息是部分代码:

// 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;
}

您的 class API 应该实现 Interface Comparable 以便您的 Set 能够检查 2 API 是否相等。

来自 java 的 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))

当您将元素添加到集合中时,它们可能不被视为相等。

您可能需要检查 API 对象的 hashCode 和 equals 方法,并覆盖它们。

这在 TDD 中很容易完成。

hashCode 在使用 HashSet 时使用(您的情况)。

另见this question about hashSet and equals methods