reduce的用法

參考網站

Question:

public static void main(String[] args) { List<String> nums = Arrays.asList("EE","SE"); String ans = nums.parallelStream().reduce("Java", (a,b)->a.concat(b)); System.out.println(ans); }

What is the result?

A. Java EEJava EESE
B. Java EESE
C. The program prints either:
Java EEJava SE
or
Java SEJava EE
D. Java EEJava SE

  • Answer: D

reduce 有三種

  • Optional<T> reduce(BinaryOperator<T> accumulator);

  • T reduce(T identity,BinaryOperator<T> accumulator); //多了一個初始值

  • U reduce(U identity,BiFunction<U,? super T,U> accumulator,BinaryOperator combiner);

stream() 與 parallelStream()的差別在於, parallelStream 是平行執行的

Example:

List<String> qwords = Arrays.asList("why ","what ","when "); BinaryOperator<String> operator = (s1,s2) -> s1.concat(s2); String sen = qwords.stream().reduce("Word: ", operator); System.out.println(sen);

Console:

Word: why what when

如果這題是parallelStream()的話, 答案會變成
Word: why Word: what Word: when


class Product{ int id; int price; public Product(int id,int price){ this.id = id; this.price = price; } public String toString() { return id + ":"+price; } } public class Test { public static void main(String[] args) { List<Product> products = new ArrayList(Arrays.asList(new Product(1, 10),new Product(2, 30),new Product(2, 30))); Product p = products.stream().reduce(new Product(4,0), (p1,p2)->{ p1.price+=p2.price; return new Product(p1.id, p1.price); }); products.add(p); System.out.println(products); products.stream().parallel().reduce((p1, p2) -> p1.price > p2.price ? p1 : p2).ifPresent(System.out::println); } }

Console:

[1:10, 2:30, 2:30, 4:70] 4:70

ifPresent()
當存在時, 執行裡面的動作

tags: ocpjp