Java 8 Stream operation

145 views Asked by At

Let's say I have a Stream of Strings called s. Is it possible to have a unary operation that converts every lone String to two Strings?

So if the original Stream contains {a,b,c} and the operation converts every single String s to s + "1" and s + "2" then we would get: {a1,a2,b1,b2,c1,c2}.

Is this possible (with a lambda expression)?

2

There are 2 answers

1
Pshemo On BEST ANSWER

Yes, you can use flatMap like

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
0
Boris the Spider On

You can do this fairly 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));
}

Usage:

final Stream<String> test = Stream.of("a", "b", "c");
multiply(test, 2).forEach(System.out::println);

Output:

a1
a2
b1
b2
c1
c2