Why doesn't Java Option 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;
    ts1.opt1.ifPresent(cns1);
    System.out.println(ts1.opt1.get());

}


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 from 100, 20, 30, 80 on average), but I create a Consumer that should increase the result by 3 ... but it does not seem to work.

Can someone help me?

+4
source share
2 answers

The action is Consumeractually executed, but the body you provided only modifies the local instance, which ultimately gets lost. The method ifPresent()should only be used to perform side effects (actions).

, Optional, map().

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

get() Optional. , orElse, orElseGet orElseThrow.

+5
Consumer<Integer> cns1 = new Consumer<Integer>() {
    public @Override void accept(Integer x) {
        // x is a local variable
        x += 3; // unboxing, adding, boxing 
        // the local variable has been changed
    }
};

.

-

ts1.opt1.map(x -> x + 3).ifPresent(System.out::println);

(, AtomicInteger):

Consumer<AtomicInteger> cns1 = x -> x.addAndGet(3);

Consumer<AtomicInteger> ( , @pivovarit ).

,

IntStream.of(100, 20, 30, 80).average().ifPresent(System.out::println);

.

+1

Source: https://habr.com/ru/post/1659803/


All Articles