almal almal - 3 months ago 19
Java Question

Why Java's Optional doesn'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 result is 57 (that is the correct result of 100, 20, 30, 80 average) but I create a Consumer that should increment the result by 3... but it seems to not work.

Can someone help me?


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(...)

Remember to be careful when using get() on an Optional instance. Before you decide to use it, have a look at orElse, orElseGet, and orElseThrow.