Friday, 12 January 2018

Using Optional.map

I found the following example of code in our code base, it was in a method that got called with a model which is a collection of ModelNodes.

Optional<ModelNode> node = model.stream().findFirst();
Optional<String> detailCode = node.isPresent() ?
  Optional.of(node.get().getValue()) : Optional.empty();

Luckily it can be rewritten a deal more concisely with the .map function available in the Optional class.

Optional<String> aangifteDetCode = model.stream().findFirst().map(ModelNode::getValue);

The codebase just got a little better.

No comments:

Post a Comment