user3680750 user3680750 - 1 year ago 89
Java Question

Java 8, collect method, creating a new arraylist and mutation

I just want to clarify something regarding the code below:

public static void ageOverTen(final List<Human> man) {
final List<Human> byAge =
.filter(age -> age.getAge() > 10)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

System.out.println("People over 10 years: " + byAge);

In the Java world we all know
is not thread safe and it's mutable, so when you create a stream and use a
method, and in it we create an
. How does the library affect
thread safety and mutation, to make it comply with functional programming concept of immutability?

Answer Source

Yes, collect() is designed to work even in parallel, even with non-thread-safe mutable data structures -- provided you follow the rules. These rules include non-interference -- that the behavioral parameters passed to the stream methods (lambdas) do not modify the source of the stream during the operation, and for most operations, statelessness -- that the lambdas do not access state that might change during the computation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download