Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return same object from Java8 lambda

Tags:

lambda

java-8

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

like image 992
robjwilkins Avatar asked Mar 14 '23 02:03

robjwilkins


1 Answers

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.

like image 107
Alexis C. Avatar answered Apr 01 '23 13:04

Alexis C.