PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] Why Java's Optional doesn't call Consumer in ifPresent()?

 September 20, 2022     consumer, java, java-8, lambda, option-type     No comments   

Issue

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 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?


Solution

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.

ts1.opt1
  .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.



Answered By - Grzegorz Piwowarek
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing