DoubleStream mapToObj() in Java

Course Curriculum

DoubleStream mapToObj() in Java

DoubleStream mapToObj() in Java

DoubleStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function.

Syntax:

<U> Stream<U>
mapToObj(DoubleFunction<?
extends U> mapper)
Parameters: This method accepts following parameters:

  • U: The element type of the new stream.
  • Stream : A sequence of elements supporting sequential and parallel aggregate operations.
  • DoubleFunction : Represents a function that accepts an double-valued argument and produces a result.
  • mapper : A stateless function to apply to each element.
  • Return Value: The function returns an object-valued Stream consisting of the results of applying the given function.

Below examples illustrate the mapToObj() method:

Example 1 :

// / Java code for DoubleStream mapToObj
// (DoubleFunction mapper)
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.DoubleStream;
class P_AI {
// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(4.5, 9.5,
5.7, 3.9);
// Using DoubleStream mapToObj(DoubleFunction mapper)
// and displaying an object-valued Stream
// consisting of the results of
// applying the given function
stream.mapToObj(num ->{return num * num * num ;})
.forEach(System.out::println);
}
}

Output:
91.125
857.375
185.193
59.318999999999996

Example 2 :

// Java code for DoubleStream mapToObj
// (DoubleFunction mapper)
import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Stream;
import java.util.stream.DoubleStream;
class P_AI {
// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(4.5,9.5,5.7,3.9);
// Creating a Stream
// Using DoubleStream mapToObj(DoubleFunction mapper)
Stream<BigDecimal> stream1 = stream
.mapToObj(BigDecimal::valueOf);
// Displaying an object-valued Stream
// consisting of the results of
// applying the given function.
stream1.forEach(num -> System.out.println
(num.add(BigDecimal.TEN)));
}
}

Output:
14.5
19.5
15.7
13.9

Character Stream Vs Byte Stream in Java (Prev Lesson)
(Next Lesson) Command Line arguments in Java
', { 'anonymize_ip': true });