Hi everyone.
This year I worked on learning more Javascript, but I continue to work with Java for my desktop works.
This week I needed to develop a small functionality extending the ERP we work with, to export a text file for compliance with a government agency.
In order to do this, and trying to use a more "functional" approach, I explored the Stream object.
This is a new functionality in the language. A Stream is a collection, that allows data processing declaratively. For instance, I needed to do a sum over an array of items. In the old days of ArrayList, this was my code:
BigDecimal total = BigDecimal.ZERO;
Iterator iterator = listOfValues.iterator();
while (iterator.hasNext()) {
TotalSsn currentElement = iterator.next();
if (currentElement.isChildrenOf(account)) {
total.add(currentElement.getImporte());
}
}
With a little help of the Stream object, the code looks like this:
BigDecimal total = BigDecimal.ZERO;
Optional<BigDecimal> totalOptional = listOfValues.stream().filter(y -> y.isChildrenOf(account)).map(TotalSsn::getImporte).reduce((a, b) -> (a.add(b)));
if (totalOptional.isPresent()) {
total = total.get();
}
In the second approach, I'm using:
stream()
This method returns a stream. It's a method of the List interface, so getting a Stream to work with is pretty straightforward on legacy code.
filter()
This method takes a functional interface as a parameter and returns a new Stream with the results of applying this function to the original stream's elements.
map()
This method allows you to generate a new Stream whith another generic type. In this case I'm converting my TotalSsn to BigDecimal.
reduce()
Allows the calculation, in this case, of a sum of the Stream values.
This whole API, I think, is worthy to be explored.
Saludos,






When using streams, the use of 'isPresent' is considered an anti-pattern, because it's just a null-check in disguise. Instead, either use 'ifPresent', or 'orElse', or 'orElseThrow'. Otherwise you're using the tools but missing the point.