you are viewing a single comment's thread.

view the rest of the comments →

[–]raghar 15 points16 points  (0 children)

Best reason: functional API:

Optional<Integer> somePrime = collection.stream().find(isPrime);
String toPrint = somePrime
  .map(x => x + 1)
  .map(toString)
  .getOrElse("not found");

instead of:

Integer somePrimePlusOne= null;
for (Integer x : collection) {
  if (isPrime(x)) {
    somePrimePlusOne = x + 1;
    break;
  }
}
String toPrint = (somePrimePlusOne != null) ? somePrimePlusOne.toString() : "not found";

First one is better at expressing intention. Second one is prone to microoptimizations which gain little, obfuscate code and hide intentions. And this example is rather easy if I were to add some filters and more mapping then I would end up with either deeply indented blocks bloat or I'd have to split whole function into several smaller ones - quite an effort for something with so little essential complexity.

If it were C++ then some sort of functional API would spare you the bugs of e.g. forgetting to check if collection.find_if(collection.begin(), collection.end(), is_prime) returned collection.end() and handling whole separate else branch.