简体   繁体   中英

How to remove the dulpicates from ArrayList<HashMap<String,Object>> in java?

I'm having a Arraylist of type HashMap. I need to eliminate the duplicate entries from the same. I was using the set to remove the duplicate as shown below.

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

But in sets we cannot store HashMap. I want the HashMap with key,value pair as the return value which will be added to the list. That is the final value should be in the format of ArrayList>.

Can you please help me in this regard. Thanks.

Set should be able to contain a HashMap.

I assume the duplicate here means key, value pair is the same between 2 HashMap. In that case, you can try

Set<HashMap<String, Object>> abc = new HashSet<HashMap<String, Object>>();
HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put("a", "a");

HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put("a", "a");

HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put("c", "c");

abc.add(a1);
abc.add(a2);
abc.add(a3);

for (HashMap<String, Object> each : abc){
    System.out.println(each.toString()); //{a=a}, {c=c}
}

EDITED based on your comment

You can reverse the value to be the key of a new HashMap. Check out the code below

String yourkey = "key";
List<HashMap<String, Object>> oldList = new ArrayList<HashMap<String, Object>>();

HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put(yourkey, "1");

HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put(yourkey, "1");

HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put(yourkey, "2");

oldList.add(a1);
oldList.add(a2);
oldList.add(a3);

HashMap<Object, Object> newMap = new HashMap<Object, Object>();
for (HashMap<String, Object> each : oldList){
    // Put the value as key. Duplicate will be overridden
    newMap.put( each.get(yourkey), each);
}

List<HashMap<String, Object>> noDuplicateList = new ArrayList<HashMap<String, Object>>();
for (Object each : newMap.keySet()) {
    noDuplicateList.add( (HashMap)newMap.get(each) );
}

System.out.println(noDuplicateList); // [{key=2}, {key=1}]

You must make sure that the 'value' is comparable (Here we use String). Otherwise, create your own equals method.

Hope it helps

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