Stream mapToDouble() in Java with examples
Last Updated :
06 Dec, 2018
Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
Where, A sequence of primitive double-valued
elements and T is the type of stream elements.
mapper is a stateless function which is applied
to each element and the function returns the new stream.
Example 1 : mapToDouble() with operation of selecting elements satisfying given function.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "10" , "6.548" , "9.12" ,
"11" , "15" );
list.stream().mapToDouble(num -> Double.parseDouble(num))
.filter(num -> (num * num) * 2 == 450 )
.forEach(System.out::println);
}
}
|
Output :
15.0
Example 2 : mapToDouble() with operation of returning a stream with square of string length.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "CSE" , "JAVA" , "gfg" ,
"C++" , "C" );
list.stream().mapToDouble(str -> str.length() * str.length())
.forEach(System.out::println);
}
}
|
Output :
9.0
16.0
9.0
9.0
1.0
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...