Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double a stream

I want to double a Stream (no DoubleStream). Meaning I start with a stream and want to get a new stream where each element of the old stream is streamed twice. So 1,2,3,4,4,5 gives us 1,1,2,2,3,3,4,4,4,4,5,5. Is there such a stream operation?

like image 365
principal-ideal-domain Avatar asked Jun 11 '15 14:06

principal-ideal-domain


People also ask

What is double Stream in Java?

A sequence of primitive double-valued elements supporting sequential and parallel aggregate operations. This is the double primitive specialization of Stream .

Can we use Stream twice?

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.

What is IntStream in Java?

public interface IntStream extends BaseStream<Integer,IntStream> A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream .

What is Java LongStream?

public interface LongStream extends BaseStream<Long,LongStream> A sequence of primitive long-valued elements supporting sequential and parallel aggregate operations. This is the long primitive specialization of Stream .


1 Answers

Create an inner stream which will contain current element two times and flatMap this stream.

stream.flatMap(e -> Stream.of(e,e))

If you want to multiply the number of elements by n you can create an utility method like this one:

public static <T> Stream<T> multiplyElements(Stream<T> in, int n) {
    return in.flatMap(e -> IntStream.range(0, n).mapToObj(i -> e));
    //  we can also use    IntStream.rangeClosed(1, n) 
    //  but I am used to iterating from 0 to n (where n is excluded)
}

(but try to use a better name for this method, since the current one may be ambiguous)

Usage example:

multiplyElements(Stream.of(1,2), 3).forEach(System.out::println);

Output:

1
1
1
2
2
2
like image 100
Pshemo Avatar answered Oct 19 '22 11:10

Pshemo