简体   繁体   中英

Delete all the entries but the specified Key set from Hash Map

I am trying to delete all the entries in HashMap apart from the specified Set of Keys. For example say HashMap numToalphaMap has entries 1-->a, 2-->b, 3-->c, 4-->d. Given KeySet is {1, 2}. I want to delete other entries ie.., (3-->c, 4-->d) from the numToalphaMap. Could anyone help me with this?

最简单的方法(在Java 8中)只是删除不在keySet任何键:

map.keySet().removeIf(k -> !keySet.contains(k));

If you are on Java 8, how about the below stream solution?

    Set<Integer> keysToKeep = new HashSet<>();
    keysToKeep.add(1);
    keysToKeep.add(2);

    Map<Integer, String> intToStringMap = new HashMap<>();
    intToStringMap.put(1, "a");
    intToStringMap.put(2, "b");
    intToStringMap.put(3, "c");
    intToStringMap.put(4, "d");


    Map<Integer, String> filteredMap = 
            intToStringMap.entrySet().stream()
            .filter(x -> keysToKeep.contains(x.getKey()))
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

Java 7 version:

    Iterator<Map.Entry<Integer, String>> entryIterator = intToStringMap.entrySet().iterator();

    while (entryIterator.hasNext()) {
        Map.Entry<Integer, String> entry = entryIterator.next();
        if(!keysToKeep.contains(entry.getKey())) {
            entryIterator.remove();
        }
    }

For performance consideration, you can first determine if the key set you can to keep is large or small. If only it's small you can create a new HashMap and assign the key-value pair in that new one. Otherwise, you can iterate and remove those aren't in the set as following:

for (Map.Entry<String, String> entry : map.entrySet()) {
   if (keySet.contains(entry.getKey())) {
     entry.remove();
   }
}

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