Convert foreach to a Java 8 filter stream

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

I tried to migrate it to Java 8 What did I do wrong?

list.stream()
    .filter(c -> !map.containsKey(Name))
    .forEach(c -> result.add(c));

But my condition has not been evaluated

Solution

It should be

list.stream().filter(c-> !map.containsKey(c)).forEach(result::add);

A better way is:

List<String> result = list.stream().filter(c -> !map.constainsKey(c)).collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>