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

标签 java hashmap duplicates hashset

我有一个 Java HashMap ,用于检索软件系统的 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;
}

最佳答案

来自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

关于java - 如何删除 Hashmap 中重复的键值对? - 不只是复​​制键或值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29946982/

相关文章:

java - 如何防止 Android Archive 库中的重复依赖

java - 利弊 : Jetbrains IntelliJ/Sublime Text

Java:将UTC日期转换为本地时区

java - 有人可以向我解释一下发生了什么事吗?有很多事情正在发生,我还没有被教导过

c++ - 如何检查 hash_map 中我的自定义哈希是否良好?

c++ - 如何在键是自定义对象的情况下使用 stdext::hash_map?

java - GridBagLayout 单元格中对象的对齐方式

java - hashmap 对象引用如何变化

javascript - 为什么单个 document.write 语句同时加载 jquery 缩小文件和完整的 jquery 文件?

Java 二维数组 - 检测重复值