Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating IntStream with index

Is it possible to iterate over an int array with IntStream but with the index?

Trying to do something like this:

ByteBuf buf = ...;
int[] anArray = ...;

IntStream.of(anArray).forEach(...); // get index so I can do "anArray[index] = buf.x"
like image 223
ImTomRS Avatar asked Jun 08 '26 01:06

ImTomRS


2 Answers

In general it's a bad idea to use Stream API to modify the source. Stream API is best suitable for processing immutable data (create new object as a result instead of mutating the existing one). If you want to fill an array using the index somehow to compute the value, you may use Arrays.setAll. For example:

int[] arr = new int[10];
Arrays.setAll(arr, i -> i*2);
// array is filled with [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] now

If you still want to use Stream API, you can generate a stream of values and dump them into array afterwards (without creating array manually):

int[] arr = IntStream.range(0, 10).map(i -> i*2).toArray();

Similarly you can generate array values which don't depend on the index. For example, from random generator:

Random r = new Random();
int[] arr = IntStream.generate(() -> r.nextInt(1000)).limit(10).toArray();

Though better to use dedicated method of Random class:

int[] arr = new Random().ints(10, 0, 1000).toArray();

If you just want to create an array filling it with the same value, you may also use generate:

int[] arr = IntStream.generate(() -> buf.x).limit(10).toArray();

Though using Arrays.fill, as @FedericoPeraltaSchaffner suggests, looks cleaner.

like image 121
Tagir Valeev Avatar answered Jun 09 '26 15:06

Tagir Valeev


You shouldn't use an IntStream to mutate the array. Instead, use the Arrays.fill() method:

Arrays.fill(anArray, buf.x);
like image 40
fps Avatar answered Jun 09 '26 14:06

fps