简体   繁体   English

删除所有条目,但从哈希映射中删除指定的密钥集

[英]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. 我试图删除HashMap中除指定的键集之外的所有条目。 For example say HashMap numToalphaMap has entries 1-->a, 2-->b, 3-->c, 4-->d. 例如,说HashMap numToalphaMap具有条目1 - > a,2 - > b,3 - > c,4 - > d。 Given KeySet is {1, 2}. 给定KeySet是{1,2}。 I want to delete other entries ie.., (3-->c, 4-->d) from the numToalphaMap. 我想从numToalphaMap中删除其他条目,即..,(3 - > c,4 - > d)。 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? 如果您使用的是Java 8,那么下面的流解决方案呢?

    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: Java 7版本:

    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. 如果只是它很小,你可以创建一个新的HashMap并在新的HashMap中分配键值对。 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();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM