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]
Archives
- July 2024
- June 2024
- May 2024
- March 2024
- February 2024
- January 2024
- December 2023
- October 2023
- September 2023
- May 2023
- March 2023
- January 2023
- December 2022
- November 2022
- October 2022
- September 2022
- August 2022
- July 2022
- April 2022
- March 2022
- November 2021
- October 2021
- September 2021
- July 2021
- June 2021
- March 2021
- February 2021
Calendar
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |