Java Stream API Example - 1Z0-809: Java SE 8 Programmer II

Java Stream API Example

Question

Given: public class product{ int id; int price; public Product (int id, int price){ this.id = id; this.price = price; } public String toString(){return id + ":" + price;} } and the code fragment: List<Product> products = 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); products.stream().parallel() .reduce((p1, p2) - > p1.price > p2.price ? p1 : p2) .ifPresent(System.out: :println); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

C.

The code given defines a class Product with two instance variables id and price, a constructor that initializes these variables, and a toString() method that returns a string representation of the product. It then creates a List of three Product objects using the Arrays.asList method, and assigns it to the variable products.

The next line of code initializes a Product object p with an id of 4 and a price of 0, and uses the reduce method to iterate over the products list and accumulate the price of all the Product objects into p. The lambda expression (p1, p2) -> { p1.price+=p2.price; return new Product (p1.id, p1.price);} takes two Product objects as input, adds their price values, and creates a new Product object with the same id as the first input Product object, and the sum of the price values as its price. This new Product object is returned and used as the first input Product object for the next iteration.

The result of this reduce operation is a Product object with an id of 4 and a price of 70 (10+30+30). This Product object is then added to the products list using the add method.

The next line of code uses the parallel method to create a parallel stream of Product objects from the products list. It then uses the reduce method to find the Product object with the highest price value, using the lambda expression (p1, p2) -> p1.price > p2.price ? p1 : p2. This lambda expression takes two Product objects as input, and returns the Product object with the higher price value.

Finally, the ifPresent method is used to print the result of the reduce operation. If the result of the operation is present, meaning that there is at least one Product object in the stream, it is printed to the console using the println method.

The result of the program is option D. The output of the println statement is 4:70, which is the id and price of the Product object with the highest price value. The products list contains four Product objects in total, with id and price values of (1, 10), (2, 30), (2, 30), and (4, 70).