Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform foreach to 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);
    }
}

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

like image 387
Marinescu Raluca Avatar asked Feb 11 '26 08:02

Marinescu Raluca


2 Answers

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());
like image 191
Eran Avatar answered Feb 13 '26 00:02

Eran


list.stream()
    .filter(c -> !map.containsKey(c))
    .collect(Collectors.toCollection(ArrayList::new));
like image 25
Ousmane D. Avatar answered Feb 13 '26 00:02

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!