java stream reduce泛型类型的arraylist

waxmsbnn  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(310)

我不太明白java stream reduce是如何工作的。
我有一个名为“catalog”的arraylist文章(泛型类型)。
文章有以下方法:

public int getUnitsInStore()
public long getUnitPrice()

为了获得目录中所有文章的总价值,我尝试使用javastreamapi的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方法是如何工作的。

ws51t4hk

ws51t4hk1#

我建议你用 Stream.reduce() 需要两个参数的重载:
identity:identity元素既是缩减的初始值,也是流中没有元素时的默认结果
累加器:采用两个参数的累加器函数:还原的部分结果和流的下一个元素。它返回一个新的部分结果。
因此,您将通过以下方式获得您的价值:

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

shyt4zoc2#

有三种类型的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", "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, (a,n) -> a + n);
    System.out.println(sum);

    int multi = Stream.of(1,2,3,4,5,6,7,8,9,10)
            .reduce(1, (a,n) -> a * n);
    System.out.println(multi);

    /**
     * Optional<T> reduce(BinaryOperator<T> accumulator)
     * 
     */

    Optional<String> optName = Stream.of("T", "O", "M", "M", "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", "a", "n")
        .reduce(0, (a,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, (a,b) -> a + b.length(), (x,y) -> x + y);
    System.out.println(sumAll);

    String csvNames = Stream.of(names)
            .reduce("", (a,b) -> a + b + ";");
    System.out.println(csvNames);
aiazj4mn

aiazj4mn3#

这个 a 以及 b 在累加器lambda中,分别是部分结果和流中的下一个元素。由于您要减少文章列表,因此部分结果是一篇文章,您不能向文章中添加long。
所以在你的情况下,你可能想这样做。

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

相关问题