1

I just want to clarify something regarding the code below:

public static void ageOverTen(final List<Human> man) {
    final List<Human> byAge = man.stream()
            .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 ArrayList is not thread safe and it's mutable, so when you create a stream and use a collect() method, and in it we create an ArrayList. How does the library affect ArrayList thread safety and mutation, to make it comply with functional programming concept of immutability?

Tom
  • 16,842
  • 17
  • 45
  • 54
  • 1
    In particular, in the linked answer: "*This also applies to any of your own non-concurrent collectors that you might implement. They can be used safely with parallel streams, provided your collectors don't interfere with the stream source, are side-effect free, order independent, etc.*" – assylias May 27 '14 at 17:43

1 Answers1

2

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.

Brian Goetz
  • 90,105
  • 23
  • 150
  • 161