2

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"
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
ImTomRS
  • 371
  • 1
  • 4
  • 10
  • 2
    If you want to mutate `anArray` why are you trying to use a stream?? – Amit Mar 09 '16 at 00:11
  • 1
    You shouldn't mutate the array (or collection) you have created a stream from, you will more than likely end up with unexpected and hard to debug results. – Gavin Mar 09 '16 at 00:17
  • See also [Is there a concise way to iterate over a stream with indices in Java 8?](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8) – Vadzim Jul 12 '18 at 19:33

2 Answers2

5

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
4

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

Arrays.fill(anArray, buf.x);
fps
  • 33,623
  • 8
  • 55
  • 110