我有一个带有以下声明的 hashMap:
Map<String, Integer> terms = new HashMap<>();
和一个列表如下:
List<String> allTerms = new ArrayList<>();
hashMap 和 List 包含字符串。
我想删除存储在 hashMap 中未在声明的列表中列出的所有字符串。 更好的方法是什么?
最佳答案
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
关于java - 从 HashMap 中删除列表中未列出的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945042/