From the list of two ʻInteger Generate a list of
Pair`s that are a combination of all the elements of each other.
ex.) [1,2,3], [5,6] -> [(1,5),(1,6),(2,5),(2,6),(3,5),(3.6)]
trial1 Maybe I can go with a map.
List<Integer> ints1 = Arrays.asList(1,2,3);
List<Integer> ints2 = Arrays.asList(5,6);
ints1.stream()
.map( i -> ints2.stream().map( j -> Pair.of(i,j)))
.collect(toList());
No good.
List <Stream <Pair <Integer, Integer >>
is returned.
In the first place ...
The Stream.map function takes the type Function <? Super T ,? extends R>
as an argument and returns <R> Stream <R>
.
Stream map(Function<? super T,? extends R> mapper) ref. Stream.map
So, the nested map is
Returns Stream <Pair <Integer, Integer >>
and
The original map that received the return value
It will return Stream <Stream <Pair <Integer, Integer >>>
.
And by the termination operation
List <Stream <Pair <Integer, Integer >>
is finally returned.
(The future will be about what the termination operation is doing ...)
By using flatMap Replace each value of Stream with another Stream, All generated Streams will be aggregated into a single Stream. ref. Java8 in Action
By definition
Passed as an argument to flatMap
The second argument of Function <? Super T ,? extends Stream <? extends R >> mapper
is
It is ? extends Stream <? extends R>
The return value is
It is <R> Stream <R>
of type R that constitutes Stream of the second argument of Function.
Stream flatMap(Function<? super T,? extends Stream<? extends R>> mapper) ref. flatMap
Based on the above, the code is as follows.
ints1.stream()
.flatMap( i -> ints2.stream().map( j -> Pair.of(i,j)))
.collect(toList());
flatMap( i -> ints2.stream().map( j -> Pair.of(i,j)))
The type returned by
With Stream <Pair <Integer, Intege >>
,
The termination operation returns List <Pair <Integer, Integer >>
.
By using flatMap It feels like it makes Stream that was nested in trial1 good ^^; (Explanation miscellaneous)
Recommended Posts