Avoid Side Effects

 class​ Inventory {
 
  List<Supply> supplies = ​new​ ArrayList<>();
 
 long​ countDifferentKinds() {
  List<String> names = ​new​ ArrayList<>();
 
» Consumer<String> addToNames = name -> names.add(name);
 
  supplies.stream()
  .filter(Supply::isUncontaminated)
  .map(Supply::getName)
  .distinct()
» .forEach(addToNames);
 return​ names.size();
  }
 }

In theory, there are no side effects with functional programming. Everything’s just a function that takes data as input and produces new data as output. The data you pass along is immutable.

But in imperative and object-oriented programming, we rely on side effects (we change data and state through procedures or methods) all the time. In Java, we can now mix all these styles. ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.