Java 8 Stream Operation
Let's say I have a stream of strings called s
. Is it possible to have a unary operation that converts every single string to two strings?
So, if the feed stream contains {a,b,c}
, and the operation converts each line s
in s + "1"
, and s + "2"
then we get: {a1,a2,b1,b2,c1,c2}
.
Is this possible (using a lambda expression)?
source to share
Yes, you can use flatMap
for example
stream.flatMap(s -> Stream.of(s + "1", s + "2"));
Example:
Stream.of("a", "b", "c") // stream of "a", "b", "c"
.flatMap(s -> Stream.of(s + "1", s + "2")) // stream of "a1", "a2", "b1", "b2", "c1", "c2"
.forEach(System.out::println);
Output:
a1
a2
b1
b2
c1
c2
source to share
You can do this quite easily using flatMap
:
public Stream<String> multiply(final Stream<String> in, final int multiplier) {
return in.flatMap(s -> IntStream.rangeClosed(1, multiplier).mapToObj(i -> s + i));
}
Using:
final Stream<String> test = Stream.of("a", "b", "c");
multiply(test, 2).forEach(System.out::println);
Output:
a1
a2
b1
b2
c1
c2
source to share