Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate every element of array via streams in Java

I have some array

int[] a = {1,2,3,4,5};

How can I get another array from this with duplicate elements via streams. I mean something like this

result = Stream.of(a).map(...)
// after that result = {1,1,2,2,3,3,4,4,5,5}
like image 325
Артур Гудиев Avatar asked Jan 02 '23 08:01

Артур Гудиев


2 Answers

You will need a flatMap instead of a map. Like,

int[] a = { 1, 2, 3, 4, 5 };
int[] result = IntStream.of(a).flatMap(x -> IntStream.of(x, x)).toArray();
System.out.println(Arrays.toString(result));

Outputs (as requested)

[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
like image 100
Elliott Frisch Avatar answered Jan 28 '23 10:01

Elliott Frisch


Here's one way to go about it:

int[] result = Arrays.stream(a)
                     .flatMap(e -> IntStream.of(e,e))
                     .toArray();

or:

int[] result = Arrays.stream(a)
                     .flatMap(e -> IntStream.generate(() -> e).limit(2))
                     .toArray();
like image 38
Ousmane D. Avatar answered Jan 28 '23 10:01

Ousmane D.