Optional[value] is getting printed

89 Views Asked by At
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

3

There are 3 best solutions below

7
On BEST ANSWER

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
0
On

Instead of using this overload of reduce that returns an Optional<Integer>1, use the overload that takes an identity element. If the list is empty, this identity element will be returned:

System.out.println(list.stream().reduce(0, PStructured01::printSum));

1 Since the source is List<Integer> and the stream is nowhere mapped to an IntStream, the result cannot be an OptionalInt.

1
On

I did this over my research, firstly thought its bit ununderstood but it was an easy concept

Optional<Integer> op = list.stream().reduce(PStructured01::printSum);

op.ifPresent(System.out::println);