(1) ifPresentOrElse(Consumer, Runnable) This new method performs the given Consumer action if a value is present, otherwise runs the given Runnable action.
IntStream.of(1, 2, 4) .filter(i -> i % 3 == 0) .findFirst() .ifPresentOrElse(System.out::println, () -> { System.out.println("No multiple of 3 found"); });
No multiple of 3 found
IntStream.of(2, 6, 8) .filter(i -> i % 3 == 0) .findFirst() .ifPresentOrElse(System.out::println, () -> { System.out.println("No multiple of 3 found"); });
6
Comparing with Java 8 Optional.isPresent(): OptionalInt opt = IntStream.of(1, 2, 4) .filter(i -> i % 3 == 0) .findFirst(); if (opt.isPresent()) { System.out.println(opt.getAsInt()); } else { System.out.println("No multiple of 3 found"); }
No multiple of 3 found
Comparing with Java 8 Optional.ifPresent(): ifPresent() method does not provide an alternative action
when the value is absent:
IntStream.of(1, 2, 4) .filter(i -> i % 3 == 0) .findFirst() .ifPresent(System.out::println);
Comparing with Java 8 Optional.orElse(): All above cases are action based. For a result assignment, we can still use orElse() method
when the value is not present.
int result = IntStream.of(1, 2, 4) .filter(i -> i % 3 == 0) .findFirst() .orElse(-1); System.out.println(result);
-1
|