简体   繁体   中英

How to remove duplicates from Hashmap of type HashMap<String, Object>?

I'm having haspmap of type <String, Object> . This hashmap contains the duplicates entries. I'm trying the below method to remove the duplicates. But its showing an error. Please find the code and error as below.

This is the original hashmap which contains data.

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

I'm trying to add the values to sets.

Set<String> valueSet = new HashSet<String>(map.values());

In the map.values() its showing an error saying that cannot resolve the constructor hashset(java.util.collection)

After this I'm adding the below code to eliminate the duplicates.

Iterator<String> it = valueSet.iterator();

        Map<Integer , String> uniqueMap = new HashMap<Integer , String>();

        while(it.hasNext()){
            String value = it.next();

            for(Entry<Integer , String> e : map.entrySet()){
                if(value.equals(e.getValue())  && !uniqueMap.containsValue(value)){
                    uniqueMap.put(e.getKey(), value);
                }
            }
        }

But due the error, I'm not able to proceed further. Could you please help me where I'm doing wrong. Thank you.

This:

Map<String , Object> map = new HashMap<String , Object>();
Set<String> valueSet = new HashSet<String>(map.values());

Doesn't work because map.values() returns a Collection<Object> and the set is of type String .

Try this:

Map<String , Object> map = new HashMap<String , Object>();
Set<Object> valueSet = new HashSet<Object>(map.values());    

Or:

Map<String , String> map = new HashMap<String , String>();
Set<String> valueSet = new HashSet<String>(map.values());  

@coders in response to your comment, if you have a list of maps and you want to create a set of this maps's unique values, you can do this:

ArrayList<HashMap<String, Object>> mDataList = new ArrayList<HashMap<String, Object>>();
Set<Object> valueSet = new HashSet<Object>();  
for(HashMap<String, Object> map : mDataList){
    valuesSet.addAll(map.values());
}

Hasmap无法存储重复的键。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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