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}
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]
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With