IntStream mapToObj() method in Java

Java 8Object Oriented ProgrammingProgramming

The mapToObj() method in the IntStream class returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.

The syntax is as follows.

<U> Stream<U>mapToObj(IntFunction<? extends U> mapper)

Here, the parameter mapper is a stateless function to apply to each element.

Create an IntStream with the range of elements using the range() method.

IntStream intStream = IntStream.range(7, 15);

Now, use the mapToObj() method.

Stream<String> s = intStream.mapToObj(a → Integer.toBinaryString(a));

The following is an example to implement IntStream mapToObj() method in Java.

Example

import java.util.*;
import java.util.stream.Stream;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.range(7, 15);
      Stream<String> s = intStream.mapToObj(a → Integer.toBinaryString(a));
      s.forEach(System.out::println);
   }
}

Output

111
1000
1001
1010
1011
1100
1101
1110
raja
Updated on 30-Jul-2019 22:30:25

Advertisements