如何在哈希图中删除重复的键值对?- 不仅仅是重复的键或值



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

[SoftwareID, SoftwareAPI] 

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

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

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

例如,当我迭代我的哈希图时,我得到,

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

从java的Set方法添加文档:

如果集合不包含元素 e2,则将指定的元素 e 添加到此集合中,以便 (e==null ? e2==null : e.equals(e2))

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

您可能需要检查 API 对象的哈希代码和等于方法,并覆盖它们。

这在TDD中很容易完成。

hashCode在使用HashSet时使用(这是你的情况)。

另请参阅有关哈希集和等于方法的问题

您的类 API 应该实现接口可比,以便您的 Set 能够检查 2 个 API 是否相等。

最新更新