How to remove duplicate values from a HashMap

血红的双手。 提交于 2019-12-11 02:48:47

问题


I don't know how can best describe my problem but here it is, I'm trying to remove the same names(values) from HashMap<String, String> map = new HashMap<String, String>();

for example if this map contain names like

    map.put("Vivaldi","Antonio");
    map.put("Belucci", "Monica");
    map.put("Gudini", "Harry");
    map.put("Verdo", "Dhuzeppe");
    map.put("Maracci", "Bruno");
    map.put("Carleone", "Vito");
    map.put("Bracco", "Luka");
    map.put("Stradivari", "Antonio");

I want to remove all entries with the value "Antonio" from it by using method removeTheFirstNameDuplicates, I looked in Google for a couple of days and all examples are close to what I want but not really what I need.

My thoughts are, I need something that will check a map and if it contains the same values in it then remove the duplicate. But how can I do this?


回答1:


You can do it with the following method which only iterates over the map once:

private static void removeTheFirstNameDuplicates(final Map<String, String> map) {
    final Iterator<Entry<String, String>> iter = map.entrySet().iterator();
    final HashSet<String> valueSet = new HashSet<String>();
    while (iter.hasNext()) {
        final Entry<String, String> next = iter.next();
        if (!valueSet.add(next.getValue())) {
            iter.remove();
        }
    }
}

The add() method on HashSet will return false if a value has already been added to the set. The method above uses this to detect that a duplicate has been found and then removes the duplicate from the HashMap by using the remove() method on the iterator.

It is worth noting that, depending on the Map implementation you use, the iteration order may not be guaranteed so which duplicate you remove is also not guaranteed.

If you were to use a TreeMap rather than a HashMap you would be certain to iterate over the map alphabetically by key e.g. Berluccio, Bracco, Carleone … Verdo. You would then always keep Stradivari and remove Vivaldi.




回答2:


Try this

    ArrayList<String> values = new ArrayList<String>();
    ArrayList<String> keys = new ArrayList<String>();

    java.util.Iterator<Entry<String, String>> iterate = map.entrySet()
            .iterator();
    while (iterate.hasNext()) {
        Entry mapEntry = iterate.next();
        String key = (String) mapEntry.getKey();
        String value = (String) mapEntry.getValue();

        values.add(value);
        keys.add(key);
    }

    for (int i = 0; i < values.size(); i++) {
        if (Collections.frequency(values, values.get(i)) > 1) {
            map.remove(keys.get(i));
        }
    }
    System.out.println(map.toString());


来源:https://stackoverflow.com/questions/22269271/how-to-remove-duplicate-values-from-a-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!