0Pricing
Java Academy · Lesson

Mapping to and from Object Streams

mapToObj and mapToInt.

Two Stream Worlds

Java has object streams (Stream<T>) and primitive streams (IntStream and friends). Mapping methods let you cross between them.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        System.out.println(IntStream.rangeClosed(1, 3).sum());
    }
}

mapToObj: Primitive to Object

mapToObj converts each primitive into an object, producing a Stream<T>.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        List<String> labels = IntStream.rangeClosed(1, 3)
            .mapToObj(n -> "item-" + n)
            .collect(Collectors.toList());
        System.out.println(labels);
    }
}

All lessons in this course

  1. IntStream and LongStream
  2. Range and Aggregate Operations
  3. Mapping to and from Object Streams
  4. Generating Primitive Streams
← Back to Java Academy