Favor Method References Over Lambdas

 class​ Inventory {
 
  List<Supply> supplies = ​new​ ArrayList<>();
 
 long​ countDifferentKinds() {
 return​ supplies.stream()
» .filter(supply -> !supply.isContaminated())
» .map(supply -> supply.getName())
  .distinct()
  .count();
  }
 }

Lambda expressions like you’ve seen them in the previous comparison can make your code more readable. But these benefits come at a price: you can’t execute lambda expressions partway—you can only run the whole stream. That means it’s hard to test parts of lambda expressions as you’d want to do in a unit test.

Above, you can see a slightly modified solution from the previous comparison: Favor Functional Over Imperative Style that uses a logical negation. It contains ...

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.