I have a Map that has some entires like
map.put("abc", 123)
map.put("def",234)
map.put("jkl", 567)
And a separate map that has entries
map.put("abc", 123)
map.put("def",234)
map.put("jddj", 567)
How can I write logic in java 8 so that I am returned "abc" and "def" as matched keys.
CodePudding user response:
Filter the keys from the second regarding if they are in the second map
// import static java.util.stream.Collectors.toSet;
Map<String, Integer> map = Map.of("abc", 123, "def", 234, "jkl", 567);
Map<String, Integer> map2 = Map.of("abc", 123, "def", 234, "j___", 567);
Set<String> keys = map.keySet().stream().filter(map2::containsKey).collect(toSet());
System.out.println(keys); // [abc, def]