I'm trying to find separate the duplicates and non-duplicates in a List by adding them to a Set and List while using Stream.filter and Stream.map
List<String> strings = Arrays.asList("foo", "bar", "foo", "baz", "foo", "bar");
Set<String> distinct = new HashSet<>();
List<String> extras = new ArrayList<>();
strings
.stream()
.filter(x -> !distinct.add(x))
.map(extra -> extras.add(extra));
At the end of this, I expect distinct to be [foo, bar, baz] and extras to be [foo, foo, bar], since there are 2 extra instances of foo and 1 of bar. However, they are both empty after I run this.
The lambdas given to the stream are never being called, which I verified by trying to print inside map:
.map(extra -> {
System.out.println(extra);
return extras.add(extra);
})
This doesn't work when I try to use put with Map either. What am I doing wrong?
Note: There may be other questions similar to this, but I'm looking for a kind of canonical answer for why this sort of stuff doesn't work with Java 8's Streams. If you can make this a more general question (even if it means completely changing it), I'd appreciate it.