简体   繁体   English

通过组合键值从哈希图中删除键

[英]Removing Keys from hashmap thru composite key value

Hey guys currently have problem with regards to removing duplicates from hashmap. 嘿,目前在从哈希图中删除重复项方面存在问题。

Some background: 一些背景:

My hashmap is in this format Map<CompositeKeyBean,ValueBean> . 我的哈希Map<CompositeKeyBean,ValueBean>格式为Map<CompositeKeyBean,ValueBean>

CompositeKeyBean is in the form (String ID, String hashvalue) ; CompositeKeyBean的形式为(String ID, String hashvalue) ;

ValueBean is an object. ValueBean是一个对象。

So if i have a hashmap with values as such: 因此,如果我有一个具有这样的值的哈希图:

(ID:1,HashValue:123),Obj1
(ID:1,HashValue:234),Obj1
(ID:1,HashValue:345),Obj1

I need to remove the duplicate keys and only have items with unique IDs. 我需要删除重复的键,并且只有具有唯一ID的项。 currently I have come up with this, But it does not seem to work, im pretty sure i am doing something wrong. 目前,我已经提出了这个建议,但是它似乎没有用,我很确定我做错了什么。

for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
    {
        String idvalue = entry.getKey().getCompositeKeyList().get(0);
        for(int i = 1; i < list.size();i++)
        {
            if(list.keySet().contains(idvalue))
            {
                list.remove(i);
            }
        }
    }

If you are expecting duplicate keys, then you can do the following way to handle it while populating the map itself: 如果期望重复的键,则可以在填充地图本身时执行以下方法来处理它:

Map<String, String> map = new HashMap<>();

if(map.containsKey("ID")){
String oldValue = map.get("ID");
//put logic to merge the value
}else{
map.put("ID","newValue");
}

My solution for this one would be to declare first an another Map which will be used to hold the number of times that a certain key has appeared in the original Map. 我对此的解决方案是首先声明另一个Map,该Map将用于保存某个键在原始Map中出现的次数。 For the second time, you can iterate the same map entrySet and remove the duplicates using the declared additional Map as reference. 第二次,您可以迭代相同的map entrySet,并使用声明的其他Map作为参考删除重复项。

Map<String, Integer> numberOfInstanceMap = new HashMap<String, Integer>(); //temporary placeholder

for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
    String idvalue = entry.getKey().getCompositeKeyList().get(0);
    if(!numberOfInstanceMap.containsKey(idvalue)) {
        numberOfInstanceMap.put(idvalue, 1); //initialize the key to 1
    } else {
        numberOfInstanceMap.replace(idValue, numberOfInstanceMap.get(idValue) + 1); //add 1 to the existing value of the key
    }
}

for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
    String idvalue = entry.getKey().getCompositeKeyList().get(0);
    Integer i = numberOfInstanceMap.get(idValue);
    if(i>1) { //remove duplicate if the key exists more than once
        list.remove(idValue);
    }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM