Search code examples
javafunctional-programmingunderscore-java

Optional[value] is getting printed


public static void main(String[] args) {
    
    printSumOfAllNumbersInList(List.of(12,45,34,22,56,65));
    printSumOfAllNumbersInListUsingFP(List.of(12,45,34,22,56,65));
}

private static void printSumOfAllNumbersInListUsingFP(List<Integer> list) {
    
    /*
     * Learning the use of reduce()
     */
    System.out.println(list.stream().reduce(PStructured01::printSum));
    
}

private static int printSum(int a,int b)
{
    int sum  =  a +b;
    return sum;
            
            
}
private static void printSumOfAllNumbersInList(List<Integer> list) {
    int sum = 0;
    for (Integer integer: list) {
        sum = sum + integer;
    }
    System.out.println(sum);
}}

I am solving the Use Case - Print the sum of all list numbers and return the sum.
I tried using the traditional approach and later tried to solve it using the Functional Approach.
But during the Functional Approach, I am getting the value - 234 as correct but as - Optional[234]
Can some one please explain the reason


Solution

  • Reduce, in this case, returns an OptionalInt and to retrieve it you need to use OptionalInt.getAsInt(). You could also do it like this.

    List<Integer> list = List.of(12,45,34,22,56,65);
    int sum = list.stream().mapToInt(a->a).sum();
    System.out.println(sum);
    

    prints

    234