是否可以将方法中的两个流合并为一个,所以只有一行return语句行?该方法应计算给定的二维双数组中每个列的总和,该数组具有哪种结构无关紧要,但该数组至少包含一个元素,并且允许非空行。非常感谢。
public static double[] sumUpCols(double[][] x) {
double[][] a = Stream.of(x).sorted((a0, a1) -> a1.length - a0.length).toArray(double[][]::new);
return IntStream.range(0, a[0].length).mapToDouble(i -> IntStream.range(0, a.length).mapToDouble(j -> i < a[j].length ? a[j][i] : 0.0).sum()).toArray();
}
public static void main(String[] args) {
double[][] x = { { 1 }, { 2, 3 }, { 4, 5, 6 }, { 5, 2 } };
System.out.println(Arrays.toString(sumUpCols(x)));
}
答案 0 :(得分:1)
public static double[] sumUpCols(double[][] x) {
// return Stream.of(x).mapToDouble((double[] row) -> DoubleStream.of(row).sum()).toArray();
return Stream.of(x)
.sorted((a0, a1) -> a1.length - a0.length)
.reduce((double[] left, double[] right) -> {
IntStream.range(0, right.length).forEach(i -> left[i] += right[i]);
return left;
}).get();
}
答案 1 :(得分:1)
不通过将数组转换为映射(其中列索引是键,值是列的总和)的映射而不进行排序的盒装试用版:
Collection<Double> values = Arrays.stream(x)
.flatMap(b -> IntStream.range(0, b.length)
.mapToObj(i -> new AbstractMap.SimpleEntry<Integer, Double>(i, b[i])))
.collect(groupingBy(e -> e.getKey(), summingDouble(v -> v.getValue())))
.values();
答案 2 :(得分:0)
并非完全是单个流遍历,但更好的方法可能是为嵌套数组标识可能的最大长度。然后将其用作索引和
public static double[] sumUpColumns(double[][] x) {
return IntStream.range(0, Stream.of(x).mapToInt(a -> a.length).max().orElse(0))
.mapToDouble(i -> Arrays.stream(x)
.mapToDouble(item -> i < item.length ? item[i] : 0.0)
.sum())
.toArray();
}
答案 3 :(得分:0)
lambda减少-无需使用 map
,flatMap
或其他 IntStream
public static double[] sumUpCols(double[][] x) {
double[][] sum = new double[][] { {0}, {} };
return( Stream.of( x ).reduce( (a1, a2) -> {
for( int i = 0; i < a1.length || i < a2.length; i++ ) {
sum[0] = Arrays.copyOf( sum[0], i + 1 );
sum[0][i] = 0;
try {
sum[0][i] += a1[i];
}
catch( ArrayIndexOutOfBoundsException ex ) {} // ignored
try {
sum[0][i] += a2[i];
}
catch( ArrayIndexOutOfBoundsException ex ) {} // ignored
}
return sum[0];
} ).get() );
}
动态扩大结果数组
也可以处理空行
获取:[12.0, 10.0, 6.0]