Java Reference
In-Depth Information
objects to their salaries so that we can calculate the sum and average . Method mapToDouble
receives an object that implements the functional interface ToDoubleFunction (package
java.util.function ). This interface's applyAsDouble method invokes an instance meth-
od on an object and returns a double value. Lines 119, 126 and 132 each pass to
mapToDouble the Employee instance method reference Employee::getSalary , which re-
turns the current Employee 's salary as a double . The compiler converts this method refer-
ence into an object that implements the functional interface ToDoubleFunction .
115 // sum of Employee salaries with DoubleStream sum method
116 System.out.printf(
117 "%nSum of Employees' salaries (via sum method): %.2f%n" ,
118 list.stream()
119
120 .sum());
121
122 // calculate sum of Employee salaries with Stream reduce method
123 System.out.printf(
124 "Sum of Employees' salaries (via reduce method): %.2f%n" ,
125 list.stream()
126 .mapToDouble(Employee::getSalary)
127
.mapToDouble(Employee::getSalary)
.reduce( 0 , (value1, value2) -> value1 + value2)
);
128
129 // average of Employee salaries with DoubleStream average method
130 System.out.printf( "Average of Employees' salaries: %.2f%n" ,
131 list.stream()
132 .mapToDouble(Employee::getSalary)
133
134 .getAsDouble());
135 } // end main
136 } // end class ProcessingEmployees
.average()
Sum of Employees' salaries (via sum method): 34524.67
Sum of Employees' salaries (via reduce method): 34525.67
Average of Employees' salaries: 4932.10
Fig. 17.16 | Summing and averaging Employee salaries.
Lines 118-120 create a Stream<Employee> , map it to a DoubleStream , then invoke
DoubleStream method sum to calculate the sum of the Employee s' salaries. Lines 125-127
also sum the Employee s' salaries, but do so using DoubleStream method reduce rather
than sum —we introduced method reduce in Section 17.3 with IntStream s. Finally, lines
131-134 calculate the average of the Employee s' salaries using DoubleStream method
average , which returns an OptionalDouble in case the DoubleStream does not contain
any elements. In this case, we know the stream has elements, so we simply call method
OptionalDouble method getAsDouble to get the result. Recall that you can also use
method orElse to specify a value that should be used if the average method was called on
an empty DoubleStream , and thus could not calculate the average.
 
Search WWH ::




Custom Search