且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从HashMap中删除重复的值

更新时间:2022-12-12 19:53:27

你可以用下面的方法来完成它: p>

  private static void removeTheFirstNameDuplicates(final Map< String,String> map){
final Iterator< Entry< String,String> &GT; 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();



code $
$ 添加()方法 HashSet 将返回 false 如果已添加一个值到集合。上面的方法使用它来检测已找到重复项,然后使用 remove()$ c从 HashMap 中删除​​重复项

值得注意的是,根据你使用的 Map 实现,如果你使用 TreeMap $ c $,那么迭代顺序可能无法保证, c>而不是 HashMap ,您肯定会按键字母顺序遍历地图Berluccio,Bracco,Carleone ... Verdo。然后,你会始终保持Stradivari并删除Vivaldi。


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?

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.