Transform foreach to Java 8 filter stream

  • A+
Category:Languages

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


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

Comment

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