I have the following code:
@Test
public void testAverageFromArray() {
final Double[] dbls = { 1.1, 1.2, 1.3, 1.4, 1.5 };
final double av = Stream.of(dbls).mapToDouble(d -> d).average().getAsDouble();
assertEquals(1.3, av, 0);
}
Question: Is it possible to replace the d -> d lambda with some other syntax? It seems needless.
*I wasnt sure about the title of this question - please edit if its off the mark.
thanks
In your code, you are converting a
Stream<Double>
to aDoubleStream
. The latter has the convenience methodaverage()
whichStream
can’t offer as it’s a generic class that can be used with arbitrary types.Thus, for the conversion of the arbitrary type
T
of aStream<T>
to thedouble
element type of aDoubleStream
, the conversion function is needed, even if it is as simple asd -> d
, when utilizing the fact that you and the compiler, unlike the stream implementation, know that the element type isDouble
which can get implicitly unboxed.Note that when the conversion function is required anyway, the method
DoubleStream.average()
stops being that convenient and you could also use:using the
import static
feature, it becomes:Just for completeness, you could even do it without a
d -> d
function usingbut, of course, this doesn’t add to readability nor brevity. It’s the explicit form of what the
summarizingDouble(…)
collector does, but in this form we can get rid of themapper
function.The lambda
d -> d
is not needless. What happens is that you need to provide a functionT -> double
. In factd -> d
is a functionDouble -> double
because the unboxing is done automatically (since Java 5).You could always replace it with a method reference
.mapToDouble(Double::doubleValue)
to make it clear that it unboxes the double value for the Double instance you're processing.