2
Map<Integer, Boolean> map1= new HashMap<>();
map1.put(1, true);
map1.put(2, true);
map1.put(3, false);
map1.put(4, true);
map1.put(5, false);

Map<Integer, Integer> map2= new HashMap<>();
map2.put(1, 1);
map2.put(2, 2);
map2.put(3, 3);
map2.put(4, 4);
map2.put(5, 5);
List<Integer> valids = new ArrayList<>();
map2.values().stream().filter(value-> map1.get(value) ? valids.add(account) : false);

When I try to output the values of the list valids it returns an empty list. Why is it so? Does the reference of the list change when doing the stream operation?

Note :I am able to add to it using the collect() method.

2
  • 8
    Don't do that. A filter function is supposed to filter. Not to have side-effects. Learn how Streams work and what are the correct and incorrect things to do. You don't have any terminal operation on the stream, so the your last line is a noop: nothing is ever filtered. The javadoc, and the hundreds of tutorials about streams, are your friends. Commented Sep 28, 2018 at 6:13
  • 2
    As a side note, map1.get(value) ? trues.add(account) : false is the same as map1.get(value) && trues.add(account) Commented Sep 28, 2018 at 11:16

2 Answers 2

1

Your code is not correct, because using filter for adding an item to list, that defeats purpose of filter.

You should terminate filter pipeline by collecting result. The stream here is Open and hence can not flush result to list;

Use:

map2.values().stream().filter(map1::get).forEach(trues::add);

Or if you want to use that way then close stream by a collector function

map2.values().stream().filter(value-> map1.get(value) ? trues1.add(value) : false).count();
Sign up to request clarification or add additional context in comments.

Comments

1

Don't do this.

A filter method is supposed to filter a stream, not add something to some other list. Also, your stream doesn't have any terminal operation - its a wrong approach.

Change it to using collect as you mentioned. It would be more readable & maintainable that way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.