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)?

+3


source to share


2 answers


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

      

+13


source


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

      

+5


source







All Articles