I am using stream API reduce to test a array list of String.
for (int i = 0; i < 100; i++)
{
Stream<String> s1 = Stream.of("aa", "ab", "c", "ad");
Predicate<String> predicate = t -> t.contains("a");
List<String> strings2 = new ArrayList<>();
s1.parallel().reduce(new ArrayList<String>(),
new BiFunction<ArrayList<String>, String, ArrayList<String>>()
{
@Override
public ArrayList<String> apply(ArrayList<String> strings, String s)
{
if (predicate.test(s))
{
strings.add(s);
}
return strings;
}
}, new BinaryOperator<ArrayList<String>>()
{
@Override
public ArrayList<String> apply(ArrayList<String> strings,
ArrayList<String> strings2)
{
return strings;
}
}).stream().forEach( //
e -> {
strings2.add(e);
});
if (strings2.contains(null))
{
System.out.println(strings2);
}
}
}
I went through couple of the blogs which says reduce could be used in this case, and the synchronization could be guaranteed, but the case above looks like this is not true. This test is TRUE in couple test runs,
strings2.contains(null)
so my question is that: Is the way in which I use reduce is incorrect, or there is something extra should be done to make sure the sych?