Sometimes we use arrays of primitive types such as char
and boolean
.
It is often possible to operate concisely by using the Stream API for arrays.
However, ʻArrays # stream cannot be applied to primitive arrays other than ʻint
, long
, double
, so make a note of what to do in such cases.
ʻArrays # stream` can be used for arrays of any object type, so how to use the wrapper class.
final Character[] array = {...};
Arrays.stream(array)
...
favorite ʻIntStream # range` is used to generate indexes for the target array and map them to the elements of the array.
final char[] array = {...};
IntStream.range(0, array.length) //Note that it is not rangeClosed
.mapToObj(i -> array[i])
...
Stream # flatMap
is convenient when you want to operate the double array by stream at once.
Example: I want to check if all the elements of a boolean
type double array are true
.
public void run() {
...
final boolean[][] table = ...;
Arrays.stream(table)
.flatMap(this::flatten)
.allMatch(Boolean::booleanValue);
}
private Stream<Boolean> flatten(final boolean[] array) {
return IntStream.range(0, array.length)
.mapToObj(i -> array[i]);
}
Recommended Posts