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

推荐答案

在本例中,Reduced返回一个OptionalInt,要检索它,您需要使用OptionalInt.getAsInt().你也可以这样做.

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

fingerprint

234

Java相关问答推荐

在spring—data中自动发现native—sql查询期间遇到重复的SQL别名[id]

';com.itextpdf.ext.html.WebColors已弃用

如何获得执行人?

Spark上下文在向Spark提交数据集时具有内容,但Spark在实际构建它时发现它为空

为什么我的在一个范围内寻找素数的程序不能像S所期望的那样工作

如何让DTO接受空字符串字段,但如果它们不为空,则应用JPA验证?

与Spring Boot相关的实体未正确保存

在Eclipse中数组的可空性

Spring安全令牌刷新和JWT签名与本地计算的签名不匹配

try 使用Spring集成和MySQL实现发件箱模式时,锁定等待超时

垃圾收集时间长,会丢弃网络连接,但不会在Kubernetes中反弹Pod

如何创建模块信息类文件并将其添加到JAR中?

A.ForEach与For(类型a:集合)

在java中使用不同的application.properties-jar而不使用Spring

具有最大共同前景像素的图像平移优化算法

接受类及其接口的Java类型(矛盾)

无限递归Java问题

[jdk21][Foreign Function&;Memory API]MemoryLayout::varHandle通过可变数组进行 struct 化的问题

spring 数据Elastic search 与 spring 启动数据Elastic search 之间的区别是什么?

如何在java中从以百分比表示的经过时间和结束日期中找到开始日期