I have the following code
Map<String, List<String>> map= new HashMap<>();
map.put("a", Arrays.asList("a1"));
map.put("b", Arrays.asList("a2"));
List<String> result = new ArrayList<>();
List<String> list = new ArrayList<>();
list.add("a");
list.add("c");
for (String names : list) {
if (!map.containsKey(names)) {
result.add(names);
}
}
And I tried to migrate it to Java 8. What am I doing wrong?
list.stream()
.filter(c -> !map.containsKey(Name))
.forEach(c -> result.add(c));
But my condition is not evaluated
First of all, it should be:
list.stream()
.filter(c-> !map.containsKey(c))
.forEach(c->result.add(c));
Second of all, it's better to use collect as the terminal Stream operation when you want to produce a List:
List<String> result =
list.stream()
.filter(c-> !map.containsKey(c))
.collect(Collectors.toList());
list.stream()
.filter(c -> !map.containsKey(c))
.collect(Collectors.toCollection(ArrayList::new));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With