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

时间:2015-04-29 14:40:15

标签: java hashmap hashset duplicate-removal

我在Java中有一个用于撤销软件系统API的散列图。所以,我有这样的事情:

  

[SoftwareID,SoftwareAPI]

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

  

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

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

例如,当我迭代我的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;
}

2 个答案:

答案 0 :(得分:3)

来自java的Set method add documentation

  如果集合中不包含元素e2,则

将指定的元素e添加到此集合中(e == null?e2 == null:e.equals(e2))

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

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

这在TDD中很容易完成。

使用哈希集时使用hashCode(这是你的情况)。

另见this question about hashSet and equals methods

答案 1 :(得分:1)

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

相关问题