在Java 8

时间:2017-12-22 22:21:13

标签: java arrays java-8 java-stream

我喜欢通过BiFunction成对组合两个通用数组。在这里,您可以看到天真的实现:

<A,B,C> C[] combine(A[] as, B[] bs, BiFunction<A,B,C> op) {
    if (as.length == bs.length) {
        C[] cs = (C[]) new Object[as.length];
        for(int i = 0; i < as.length; i++) {
            cs[i] = op.apply(as[i], bs[i]);
        }
        return cs;
    } else {
        throw new IllegalArgumentException();
    }
}

我想知道是否有更优雅的方法可以在没有for循环的情况下执行此操作 - 可能使用Java 8 Stream。我很高兴你的建议。

2 个答案:

答案 0 :(得分:5)

您可以使用z function方法:

file '/usr/local/bin/python' do # or .../python3 if you prefer
  owner 'root'
  group 'root'
  mode '755'
  content "#!/bin/sh\nexec scl enable rh-python35 -- python3 \"$@\""
end

或者,如果计算C[] cs = (C[]) new Object[as.length]; Arrays.setAll(cs, i -> op.apply(as[i], bs[i])); 非常昂贵,您也可以使用op

答案 1 :(得分:3)

您可以使用IntStream.range生成索引,然后对其进行操作。

C[] cs = (C[])IntStream.range(0, as.length)
                       .mapToObj(i -> op.apply(as[i], bs[i]))
                       .toArray();