Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream.reduce(Float,BinaryOperator) BinaryOperator refers which functional interface method?

For Example,

List<Product> productsList = new ArrayList<Product>();  
productsList.add(new Product(1,"HP Laptop",25000f));  
productsList.add(new Product(2,"Dell Laptop",30000f));  
productsList.add(new Product(3,"Lenevo Laptop",28000f));  
productsList.add(new Product(4,"Sony Laptop",28000f));  
productsList.add(new Product(5,"Apple Laptop",90000f));  

Float totalPrice = productsList.stream()  
                               .map(product->product.price)  
                               .reduce(0.0f,(sum, price)->sum+price);   
System.out.println(totalPrice); 

Here which is the functional interface, (sum, price)->sum+price is referring to?

like image 929
Rence Abishek Avatar asked Jan 30 '19 09:01

Rence Abishek


2 Answers

Because you mentioned "functional interface method": reduce is actually calling apply of BiFunction (from which BinaryOperator extends).

like image 73
Roland Avatar answered Nov 06 '22 23:11

Roland


Look at the Stream Javadoc:

T reduce(T identity, BinaryOperator<T> accumulator)

(sum, price)->sum+price implements a BinaryOperator<Float> in your example.

This functional interface has a method that accepts two arguments of the same type (Float in your case) and returns a result of that same type.

like image 24
Eran Avatar answered Nov 06 '22 23:11

Eran