簡體   English   中英

將 function 累積應用於任何類型列表中的每個元素

[英]Applying function cumulative to every elements from list of any type

我有像List<T>這樣的對象列表,其中T可以是任何類型。 我需要 function ,它返回T類型的 object - 這將是對List<T>中的每個 object 累積應用Function<T,T,T> > 的結果。

例子:

對於List<Integer> integers = [3,1,9]Function<Integer, Integer> = (a,b) -> a+b作為結果,我應該收到13 但是對於 function Function<Integer, Integer> = (a,b) -> a*b結果將是27

您正在尋找 Stream.reduce function:給定一個列表和一個二元運算符:

List<Integer> integers = List.of(3, 1, 9);
BinaryOperator<Integer> add = (a,b)  -> a + b;
BinaryOperator<Integer> multiply = (a,b) -> a * b;

reduce function 將二元運算符應用於列表中的每個項目以及上一步的結果:

Integer sum = integers.stream().reduce(0, add); // = 0+3+1+9 = 13
Integer product = integers.stream().reduce(1, multiply); // = 1*3*1*9 = 27

還有一個變體不需要初始元素,但它返回Optional來處理列表為空的情況。

Optional<Integer> sum = integers.stream().reduce(add);
Optional<Integer> product = integers.stream().reduce(multiply);

更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM