Skip to content

Instantly share code, notes, and snippets.

@sroccaserra
Last active December 6, 2017 16:44
Show Gist options
  • Save sroccaserra/9cbffb60d3cc32295dd6 to your computer and use it in GitHub Desktop.
Save sroccaserra/9cbffb60d3cc32295dd6 to your computer and use it in GitHub Desktop.
Examples of filter, map, and reduce in Java 8
final List<String> integerStrings = Arrays.asList("1", "1", "", "3", null, "5");
final Set<Integer> integers = integerStrings.stream()
.filter(StringUtils::isNotBlank)
.map(Integer::valueOf)
.collect(Collectors.toSet());
final Integer id = 5;
final List<Double> valuesForThisId = Arrays.asList(0.54, 1.25, 2.49, null);
final double sumForThisId = identifiedAndIndexedObjectList.stream()
.filter(x -> id.equals(x.getId())) // lambda expression
.map(IdentifiedAndIndexedObject::getIndex) // reference to instance method
.map(valuesForThisId::get) // reference to bound instance method
.filter(Objects::nonNull) // reference to static method
.reduce(0.0, Double::sum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment