Check the keys in the map matching with the List content in Java
We can try adding the list to a set, then comparing that set with the keyset from your hashmap:
List<String> ll = new ArrayList<>();
ll.add("a");
ll.add("b");
ll.add("d");
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.put("b", 1);
m.put("c", 1);
Set<String> set = new HashSet<String>(ll);
if (Objects.equals(set, m.keySet())) {
System.out.println("sets match");
}
else {
System.out.println("sets do not match");
}
Every key in the map needs to present in the list else I need to throw an exception
You could do it using Stream.anyMatch
and iterating on the keyset
of the map instead as (variable names updated for readability purpose) :
if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
throw new CustomException("");
}
Better and as simple as it gets, use List.containsAll
:
if(!list.containsAll(map.keySet())) {
throw new CustomException("");
}
Important: If you can trade for O(n)
space to reduce the runtime complexity, you can create a HashSet
out of your List
and then perform the lookups. It would reduce the runtime complexity from O(n^2)
to O(n)
and the implementation would look like:
Set<String> allUniqueElementsInList = new HashSet<>(list);
if(!allUniqueElementsInList.containsAll(map.keySet())) {
throw new CustomException("");
}