简体   繁体   中英

Removing Values From a Map in a loop

I am trying to compare two maps and remove values from one map that are contained in a second map. Here is the code:

    HashMap<String, String> firstMap = new HashMap<>();
    HashMap<String, String> secondMap = new HashMap<>();

    firstMap.put("keyOne", "valueOne");
    firstMap.put("keyTwo", "valueTwo");
    firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");

    System.out.println("\nMAP ONE\n" + firstMap +  "\n");

    secondMap.put("keyOne", "valueOne");
    secondMap.put("keyTwo", "valueTwo");

    System.out.println("\nMAP TWO\n" + secondMap +  "\n");

    Iterator<String> firstMapIterator = firstMap.keySet().iterator();

    if(!firstMap.equals(secondMap)){

            firstMapIterator.next();

            for(String key : firstMap.keySet()){

                if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
                    firstMapIterator.remove();
                    break;
                }
            }
    }
    System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap +  "\n");

Now, the code does remove an element from the map but not the one I was expecting. As you can see in the code in firstMap I have entered a third key of which is the one I expect to be removed. However, this is the final contents of firstMap I seem to be getting.

{keyOne=valueOne, THIS KEY WILL BE REMOVED=valueThree}

Any ideas? Thanks

Edit: The goal of this code is to: - Compare two maps - Increment through each key - Remove key from firstMap if it is not found in secondMap

You can do this in just one line:

    HashMap<String, String> firstMap = new HashMap<>();
    HashMap<String, String> secondMap = new HashMap<>();

    firstMap.put("keyOne", "valueOne");
    firstMap.put("keyTwo", "valueTwo");
    firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");

    System.out.println("\nMAP ONE\n" + firstMap + "\n");

    secondMap.put("keyOne", "valueOne");
    secondMap.put("keyTwo", "valueTwo");

    System.out.println("\nMAP TWO\n" + secondMap + "\n");

    // Remove everything from firstMap that is in secondMap.
    firstMap.keySet().removeAll(secondMap.keySet());

    System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");

See the JavaDoc for Map.keySet() :

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa . ... The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations....

You don't need to iterate over the maps.

You can simply do

firstMap.keySet().removeAll(secondMap.keySet());

This will remove all keys from the first map that are present in the second map.

Also, you can remove all keys in the first map that are not in the second map using:

firstMap.keySet().retainAll(secondMap.keySet());

You are not using the iterator correctly. You only advance the iterator once ( firstMapIterator.next() ), so the first key obtained by the iterator will be the one removed from the Map, regardless of the current key in the for(String key : firstMap.keySet()) loop.

You don't need the for loop:

Iterator<String> firstMapIterator = firstMap.keySet().iterator();
while (firstMapIterator.hasNext()) {
    if(!secondMap.containsKey(firstMapIterator.next())) {
        firstMapIterator.remove();
        break;
    }
}

As others have already said, you can do it in one single line:

firstMap.keySet().removeAll(secondMap.keySet());

Another way would be by using the Collection.removeIf method:

firstMap.keySet().removeIf(k -> secondMap.containsKey(k));

The above can be rewritten as follows:

firstMap.keySet().removeIf(secondMap::containsKey);

check your firstMapIterator.next(); add into for loop

 HashMap<String, String> firstMap = new HashMap<String, String>();
                HashMap<String, String> secondMap = new HashMap<String, String>();

                firstMap.put("keyOne", "valueOne");
                firstMap.put("keyTwo", "valueTwo");
                firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");

                System.out.println("\nMAP ONE\n" + firstMap +  "\n");

                secondMap.put("keyOne", "valueOne");
                secondMap.put("keyTwo", "valueTwo");

                System.out.println("\nMAP TWO\n" + secondMap +  "\n");

                Iterator<String> firstMapIterator = firstMap.keySet().iterator();

                if(!firstMap.equals(secondMap)){



                    for(String key : firstMap.keySet()){
                        firstMapIterator.next();//add here in for loop
                        if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
                            firstMapIterator.remove();
                            break;
                        }
                    }
                }
                System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap +  "\n");

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