4

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?

Richard Miskin
  • 1,260
  • 7
  • 12
Predict_it
  • 247
  • 2
  • 4
  • 13

2 Answers2

5

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.

Richard Miskin
  • 1,260
  • 7
  • 12
0

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());
Richard Miskin
  • 1,260
  • 7
  • 12
Abiel Paltao
  • 315
  • 2
  • 12