Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I perform bulk array operations using lambdas?

There is a new method setAll in the java.util.Arrays class that will perform a bulk assignment of every element of an array. For example, the following code:

String[] array = ... ;
Arrays.setAll(array, String::valueOf);

will set each element of a String array to the string representation of the element’s index.

There are also overloads for setting all elements of int, long, and double arrays, as well
as companion parallelSetAll methods that run in parallel.

Unfortunately, there are no similar methods that deal with array subranges, nor are there methods that can deal with arrays whose element type
is something other than a reference type or the three specialized primitives int, long, or double. Fortunately, it’s fairly simple to use IntStream.range to generate a range of array indexes and to use stream operations to perform the array operation that you want.

For example, to increment the value within a subrange of an int array, do the following:

int[] array = ... ;
IntStream.range(startInclusive, endExclusive)
    .forEach(i -> array[i]++);

To set the elements of a byte array, do the following:

byte[] bytes = ... ;
IntStream.range(0, bytes.length)
    .forEach(i -> bytes[i] = (byte)i);

To create an IntStream from a char array, do the following:

char[] chars = ... ;
IntStream.range(0, chars.length)
    .map(i -> chars[i])
    ....