Java 9

Stream/Optional API Additions

Grzegorz Piwowarek

 

@pivovarit

@pivovarit

@pivovarit

Optional#get

http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html

@Deprecated?

@pivovarit

Optional#ifPresentOrElse
findById(42)
    .ifPresentOrElse(
        this::log,
        this::logError);
Optional#or
Optional<User> user = 
  findById(42).or(() -> findByName("Adam"))

@pivovarit

Optional#stream
list.stream()
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());
list.stream()
    .flatMap(Optional::stream)
    .collect(toList());

@pivovarit

Stream#ofNullable
 Stream.of("Maria", "Robert", "Krzysztof")
    .flatMap(n -> ofNullable(findByName(n)))
    .findAny()

@pivovarit

Stream#takeWhile/dropWhile
IntStream.iterate(0, i -> 2 * i)
    .takeWhile(i -> i < 42)
    .forEach(...)
IntStream.iterate(0, i -> 2 * i)
    .dropWhile(i -> i < 42)
    .forEach(...)

@pivovarit

Stream#iterate

Stream.iterate(1, i -> i <= 42, i -> 2 * i)

@pivovarit

Collectors#filtering

@pivovarit

.collect(
  groupingBy(User::getName, 
  filtering(user -> user.getValue() > 15_000, toList())));
Collectors#flatmapping

@pivovarit

.collect(
  groupingBy(User::getName,
  flatMapping(User::getChildren, toList())));

Thank you!

@pivovarit

Java 9 Stream/Optional API Enhancements

By Grzegorz Piwowarek

Java 9 Stream/Optional API Enhancements

  • 8,072