Check the keys in the map matching with the List content in Java

  • A+

I have a List of Strings and a Map. Every key in the map needs to present in the list else I need to throw an exception. As of now I am looping the list and checking the key and throw exception if the map doesn't contains the key. Below is the sample code is what I am doing. IS there any other way in Java8 we can do it in one line or something using streams and filters ?

And also the contents in the list and keys in the map should match. That I am already handling in the separate if condition.

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

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(""); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: