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