Favor Functional Over Imperative Style

 class​ Inventory {
 
  List<Supply> supplies = ​new​ ArrayList<>();
 
 long​ countDifferentKinds() {
» List<String> names = ​new​ ArrayList<>();
 for​ (Supply supply : supplies) {
 if​ (supply.isUncontaminated()) {
  String name = supply.getName();
 if​ (!names.contains(name)) {
  names.add(name);
  }
  }
  }
 return​ names.size();
  }
 }

When it comes to working with collections, a functional programming style can be much more readable than its imperative sibling.

Above, you can see a short but relatively complex method that does some very common things: it iterates over a collection and does a few conditional computations. Even though the code’s short and named properly, you need a moment to ...

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.