Java Stream 减少泛型类型的 ArrayList

如何解决Java Stream 减少泛型类型的 ArrayList

我不太明白 Java Stream Reduce 的工作原理。

我有一个名为“目录”的文章(通用类型)的 ArrayList。

一篇文章有​​以下方法

public int getUnitsInStore()
public long getUnitPrice()

为了获得目录中所有文章的总价值,我尝试使用 Java Stream Api 的 Reduce 方法。 (请不要使用循环提供 anwser,我已经知道怎么做)

我尝试了以下操作:

long value = 0;
    
value = catalog.stream().reduce((a,b) -> a.getUnitPrice()*b.getUnitsInStore());

但这给了我错误

Type mismatch: cannot convert from Optional<Article> to long

我做错了什么?正如我所说,我不确定我是否真的了解 reduce 方法的工作原理。

解决方法

累加器 lambda 中的 ab 分别是部分结果和流中的下一个元素。由于您正在减少文章列表,因此部分结果是文章,您不能向文章添加 Long。

所以在你的情况下,你可能想要做这样的事情。

value = catalog.stream()
            .map(a -> a.getUnitPrice() * a.getUnitsInStore())
            .reduce(0L,Long::sum);
,

reduce 方法一共有三种。 试试这个代码以更好地理解它

    /**
     * T reduce(T identity,BinaryOperator<T> accumulator)
     * 
     * identity = initial value
     * accumulator = first process initial value to first element of the stream,* then process the result with the next element in the stream
     */
     
    String name = Stream.of("T","O","M","Y")
            .reduce("",(a,n) -> a + n);
    System.out.println(name);
    
    int sum = Stream.of(1,2,3,4,5,6,7,8,9,10)
            .reduce(0,n) -> a + n);
    System.out.println(sum);

    int multi = Stream.of(1,10)
            .reduce(1,n) -> a * n);
    System.out.println(multi);
    
    
    /**
     * Optional<T> reduce(BinaryOperator<T> accumulator)
     * 
     */
    
    Optional<String> optName = Stream.of("T","Y")
            .reduce((a,n) -> a + n);
    
    if(optName.isPresent()){
        System.out.println(" get from optional --> " + optName.get());
    } 
    
    /**
     * <U> U reduce​(U identity,BiFunction<U,​? super T,​U> accumulator,BinaryOperator<U> combiner)
     * 
     * This method signature is used when we are dealing with different types.
     * It allows Java to create intermediate reductions and then combine them at the end.
     */
    
    int total = Stream.of("R","a","z","v","n")
        .reduce(0,b) -> a + b.length(),(x,y) -> x + y);
    
            // 0 = initial value type int
            // a = int,must match the identity type
            // b.method() return type must match the a and the identity type
            // x,y from BinaryOperator 
    
    System.out.println(total);
    
    
    String names[] = {"Bobby","Mark","Anthony","Danna"};
    
    int sumAll = Stream.of(names)
            .reduce(0,y) -> x + y);
    System.out.println(sumAll);
    
    String csvNames = Stream.of(names)
            .reduce("",b) -> a + b + ";");
    System.out.println(csvNames);
    
,

我建议您使用需要两个参数的 Stream.reduce() 重载:

  • identity:identity 元素既是归约的初始值,也是如果流中没有元素的默认结果
  • accumulator:累加器函数,它接受两个参数:减少的部分结果和流的下一个元素。它返回一个新的部分结果。

因此,您将使用以下方法获得价值:

value = catalog
        .stream()
        .reduce(0L,(partialSum,nextElement) -> partialSum + nextElement.getUnitPrice() * nextElement.getUnitsInStore());

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?