繁体   English   中英

从列表中未列出的HashMap中删除字符串

[英]Remove strings from HashMap not listed in a List

我有一个带有以下声明的hashMap:

Map<String, Integer> terms = new HashMap<>();

和一份清单如下:

List<String> allTerms = new ArrayList<>();

hashMap和List包含字符串。

我想删除存储在hashMap中的所有字符串,这些字符串未在声明的List中列出。 有什么更好的方法呢?

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    static boolean match = true;

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<String, Integer>();
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        List<String> list = Arrays.asList("Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7");
        map.put("Test1", 1);
        map.put("Test66", 2);
        map.put("Test3", 3);
        map.put("Test4", 4);
        map.put("Test123", 5);


        map.forEach((k, v) -> {
            match = false;
            list.forEach(s -> {
                if (k.equals(s))
                    match = true;
            });
            if(match)
                map1.put(k,v);
        });
        map = map1;
        map.forEach((k,v)->System.out.println(k));
    }
}

输出:

Test1
Test4
Test3

暂无
暂无

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

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