almal almal - 1 year ago 65
Java Question

Java Optional don't call Consumer in ifPresent

public class TestSupplier {

Optional<Integer> opt1;

public static void main(String[] args) {
// TODO Auto-generated method stub

TestSupplier ts1 = new TestSupplier();

ts1.opt1 = ts1.average(100,20,30,80);
Consumer<Integer> cns1 = (x) -> x += 3;


private Optional<Integer> average(int... n1) {
if (n1.length == 0) return Optional.empty();
int sum = 0;
for(int score: n1) sum += score;
return Optional.of(sum/n1.length);



when i run the code the resut is 57 (that is the correct result of 100,20,30,80 average) but i create a Consumer that should be increment the result by 3....but it seem doesn't work.

Someone can help me?

Answer Source

The Consumer action is actually being run but the body you provided modifies only a local instance which eventually gets lost. The ifPresent() method should be used for performing side-effects(actions) only.

If you want to perform a calculation on a value held by an Optional instance, use map() instead.

  .map(x -> x + 3).orElseThrow(...)

Try to avoid using get() on an Optional instance. This method will be deprecated in Java 9 because it essentially transforms NullPointerException into a NoSuchElementException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download