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
- IntStream and LongStream
- Range and Aggregate Operations
- Mapping to and from Object Streams
- Generating Primitive Streams