Arrays.setAll不能使用布尔值

The*_*orm 4 java arrays lambda boolean java-8

我想创建一个大数组,并想尝试一些lambda,但由于某种原因:

cells = new boolean[this.collums][this.rows];
IntStream.range(0, cells.length).forEach(x -> Arrays.setAll(cells[x], e -> MathX.fastNextInt(1) == 0 ? true : false));
Run Code Online (Sandbox Code Playgroud)

不会工作,即使这样:

cells = new boolean[this.collums][this.rows];
IntStream.range(0, cells.length).forEach(x -> Arrays.setAll(cells[x], e -> true));
Run Code Online (Sandbox Code Playgroud)

不适用.

编译器错误是:

类型不匹配:无法从布尔值转换为T.

和:

Arrays类型中的方法setAll(T [],IntFunction)不适用于参数(boolean [],(e) - > {})

And*_*niy 8

因为它应该是引用类型Boolean::

Boolean[][] cells = new Boolean[this.collums][this.rows];
Run Code Online (Sandbox Code Playgroud)

UPD:如果你想使用boolean类型,你必须setAll()为原始布尔类型编写自己的实现:

interface BooleanUnaryOperator {
    boolean apply(int x);
}

public static void setAll(boolean[] array, BooleanUnaryOperator generator) {
    for (int i = 0; i < array.length; i++)
        array[i] = generator.apply(i);
}
Run Code Online (Sandbox Code Playgroud)

UPD-2:正如@Holger所提到的,这个名称BooleanUnaryOperator具有误导性,为此目的最好使用现有的类 - IntPredicate.(在这种情况下array[i] = generator.apply(i);改为array[i] = generator.test(i);)

  • @TheSorm当然会因为自动装箱布尔值而变慢.正如提示一样,尝试用`Boolean.TRUE`替换`e - > true`(和分别用`Boolean.FALSE`替换`false`) - 处理`Boolean [] []`类型时 (3认同)