Return same object from Java8 lambda

2019-05-06 04:00发布

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

标签: lambda java-8
2条回答
Juvenile、少年°
2楼-- · 2019-05-06 04:30

In your code, you are converting a Stream<Double> to a DoubleStream. The latter has the convenience method average() which Stream 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 a Stream<T> to the double element type of a DoubleStream, the conversion function is needed, even if it is as simple as d -> d, when utilizing the fact that you and the compiler, unlike the stream implementation, know that the element type is Double 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:

final double av = Stream.of(dbls).collect(Collectors.averagingDouble(d -> d));

using the import static feature, it becomes:

final double av = Stream.of(dbls).collect(averagingDouble(d -> d));

Just for completeness, you could even do it without a d -> d function using

final double av = Stream.of(dbls).collect(DoubleSummaryStatistics::new,
        DoubleSummaryStatistics::accept, DoubleSummaryStatistics::combine)
    .getAverage();

but, 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 the mapper function.

查看更多
老娘就宠你
3楼-- · 2019-05-06 04:43

The lambda d -> d is not needless. What happens is that you need to provide a function T -> double. In fact d -> d is a function Double -> 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.

查看更多
登录 后发表回答