我有一个 List
的 Strings
和一个 Map
。 map 中的每个键都需要出现在列表中,否则我需要抛出异常。截至目前,我正在循环列表并检查键并在 map 不包含键时抛出异常。下面是我正在做的示例代码。在 Java8 中是否有任何其他方法我们可以使用 streams
和 filters
在一行中完成?
并且列表中的内容和 map 中的键也应该匹配。我已经在单独的 if 条件下处理了。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestClass {
public static void main(String[] args) {
List<String> ll = new ArrayList<>();
Map<String, Integer> m = new HashMap<>();
ll.add("a");
ll.add("b");
ll.add("d");
m.put("a", 1);
m.put("b", 1);
m.put("c", 1);
if(ll.size() != m.size){
System.out.println("Throw Exception");
}
for(String s : ll) {
if(!m.containsKey(s)) {
System.out.println("Throw Exception");
}
}
}
}
最佳答案
Every key in the map needs to present in the list else I need to throw an exception
你可以使用 Stream.anyMatch
来做到这一点并在 map 的 keyset
上迭代而不是(为了便于阅读而更新变量名称):
if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
throw new CustomException("");
}
越简单越好,使用 List.containsAll
:
if(!list.containsAll(map.keySet())) {
throw new CustomException("");
}
重要:如果您可以用 O(n)
空间来降低运行时复杂度,则可以从您的代码中创建一个 HashSet
List
然后执行查找。它将运行时的复杂性从 O(n^2)
降低到 O(n)
并且实现看起来像:
Set<String> allUniqueElementsInList = new HashSet<>(list);
if(!allUniqueElementsInList.containsAll(map.keySet())) {
throw new CustomException("");
}
关于java - 检查映射中的键是否与Java中的List内容匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54141672/