【问题标题】:Finding Duplicates in the Value of HashMap在 HashMap 的值中查找重复项
【发布时间】:2018-01-18 15:02:20
【问题描述】:
private HashMap <Integer, String> ID_TAGS;
    private HashMap <String, Integer> TAGS_ID;
    private HashMap <String, String> TAGS_TRANSLATIONS;
    private final ArrayList <Integer> INCLUSIONLIST;
    private final ArrayList <Integer> EXCLUSIONLIST;



public DuplicationFinder(HashMap <Integer, String> id_tags, HashMap <String, String> tags_translations, ArrayList <Integer> exclusionList, ArrayList <Integer> inclusionList) {
    this.ID_TAGS = id_tags;
    this.TAGS_TRANSLATIONS = tags_translations;
    this.INCLUSIONLIST = inclusionList;
    this.EXCLUSIONLIST = exclusionList;
    TAGS_ID = new HashMap <>();
    for(Entry <Integer, String> e : ID_TAGS.entrySet()){
        TAGS_ID.put(e.getValue(), e.getKey());
    }
}
/**
 * Findet die Duplikate und gibt die ID's zurück.
 * @return
 */
public Set <Integer> findDuplicates(){
    Set <Integer> duplicates = new LinkedHashSet <>();
    for(Entry <Integer, String> e : ID_TAGS.entrySet()) {
        HashMap <String, String> cloneWithoutTag= new HashMap <>(TAGS_TRANSLATIONS);
        int id = e.getKey();
        String tag = e.getValue();
        cloneWithoutTag.remove(tag);
        if(cloneWithoutTag.containsValue(TAGS_TRANSLATIONS.get(tag))) {
            duplicates.add(id);
        }
    }
    duplicates.addAll(EXCLUSIONLIST);
    duplicates.removeAll(INCLUSIONLIST);
    Iterator<Integer> nextD = duplicates.iterator();
    while(nextD.hasNext()) {
        System.out.println(lookUp(ID_TAGS.get(nextD.next())));
    }
    return duplicates;
}

public String lookUp(String tag) {
    return TAGS_TRANSLATIONS.get(tag);
}

public int getID(String tag) {
    return TAGS_ID.get(tag);
}

}

我不知道是否有人可以帮助我。我会尝试在 TAGS_TRANSLATIONS-HashMap 中找到一些具有相同值的键。 My thought was that when the chosen key is not int the clone of the map you can look if the same value is still in there.到目前为止它正在工作,但我有一个问题,像“会议”这样的一些值只有一次在那里,也进入了输出。现在我将尝试找到错误。提前感谢您的帮助:)

【问题讨论】:

  • 你的代码实际上做了什么?你把这个丢给我们,然后要求我们修复它。
  • 是的,这就是我试图解释的,我有带有 的 HashMap,这些标签指的是一个标签,我在另一个 HasMap 中实现了它。现在我尝试在翻译中查找重复项,我想将 ID 添加到重复集。但我里面有大约 10 个重复项,不是没有重复项
  • 我在下面尝试了一个答案,因为您的上述评论使问题足够清楚,可以知道您要问什么。为了将来参考,请提出更清晰的问题。

标签: java collections hashmap contains


【解决方案1】:

假设您有以下地图:

Map<Tags, Translation> someMap;

您可以将所有值作为一个集合获取,其中包括重复项,然后使用Collections#frequency() 查找每个项目的频率。如果频率大于一,则翻译为重复。

Collection<Translation> translations = someMap.values();
Set<Translation> dupeSet = new HashSet<>();

for (Translation t : translations) {
    if (Collections.frequency(translations, t) > 1) {
        dupeSet.add(t);
    }
}

请注意,此代码会触及每个重复的翻译,但由于我们将重复的翻译存储在一个集合中,因此给定的重复翻译在最终结果中应该只出现一次。

【讨论】:

  • 感谢您的回答,我的方式略有不同。我现在使用一个包装器类,这让这变得非常容易。问题是我比较了来自 2 个数据库的数据,并且一些标签的 ID 相同,所以这里的问题是集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 2016-10-16
  • 1970-01-01
  • 2016-04-10
  • 2016-03-31
  • 2021-09-02
相关资源
最近更新 更多