Mapping a Numeric Stream to an Object Stream – Streams
Mapping a Numeric Stream to an Object Stream
The mapToObj() method defined by the numeric stream interfaces transforms a numeric stream to an object stream of type R, and the boxed() method transforms a numeric stream to an object stream of its wrapper class.
The query below prints the squares of numbers in a given closed range, where the number and its square are stored as a pair in a list of size 2. The mapToObj() intermediate operation at (2) transforms an IntStream created at (1) to a Stream<List<Integer>>. Each list in the result stream is then printed by the forEach() terminal operation.
IntStream.rangeClosed(1, 3) // (1) IntStream
.mapToObj(n -> List.of(n, n*n)) // (2) Stream<List<Integer>>
.forEach(p -> System.out.print(p + ” “)); // [1, 1] [2, 4] [3, 9]
The query above can also be expressed as shown below. The boxed() intermediate operation transforms the IntStream at (3) into a Stream<Integer> at (4); in other words, each int value is boxed into an Integer which is then mapped by the map() operation at (5) to a List<Integer>, resulting in a Stream<List<Integer>> as before. The compiler will issue an error if the boxed() operation is omitted at (4), as the map() operation at (5) will be invoked on an IntStream, expecting an IntUnaryFunction, which is not the case.
IntStream.rangeClosed(1, 3) // (3) IntStream
.boxed() // (4) Stream<Integer>
.map(n -> List.of(n, n*n)) // (5) Stream<List<Integer>>
.forEach(p -> System.out.print(p + ” “)); // [1, 1] [2, 4] [3, 9]
The examples above show that the IntStream.mapToObj() method is equivalent to the IntStream.boxed() method followed by the Stream.map() method.
The mapToObj() method, in conjunction with a range of int values, can be used to create sublists and subarrays. The query below creates a sublist of CD titles based on a closed range whose values are used as an index in the CD list.
List<String> subListTitles = IntStream
.rangeClosed(2, 3) // IntStream
.mapToObj(i -> CD.cdList.get(i).title()) // Stream<String>
.toList(); // [Lambda Dancing, Keep on Erasing]
Leave a Reply