是否有可能在Java中从2个流中生成一个新流?
我对Java8流还很陌生,我面临一个问题,为大学做作业。 如果我有两个整数流,它们的整数数量与是否有可能在Java中从2个流中生成一个新流?,java,java-8,java-stream,Java,Java 8,Java Stream,我对Java8流还很陌生,我面临一个问题,为大学做作业。 如果我有两个整数流,它们的整数数量与 intstreamone=Arrays.stream(test.matrix).flatMapToInt(Arrays::stream); IntStream two=Arrays.stream(test2.matrix).flatMapToInt(Arrays::stream); IntStream差=1-2??? 是否有可能生成一个新的流,其中包含两个流的差异所在的元素? 我尝试了很多,比如使用
intstreamone=Arrays.stream(test.matrix).flatMapToInt(Arrays::stream);
IntStream two=Arrays.stream(test2.matrix).flatMapToInt(Arrays::stream);
IntStream差=1-2???
是否有可能生成一个新的流,其中包含两个流的差异所在的元素?
我尝试了很多,比如使用stream.iterator()代码>,但我不允许使用“普通”迭代器,应该使用lambda表达式来解决它。
有人知道如何解决这个问题吗?
亲切问候,,
Lukas组合两个流/列表的操作通常称为zip
。
不幸的是,Java 8标准库中没有提供此操作。
您可以在此处阅读更多关于用户如何定义自己的zip函数的信息:总体而言,您基本上只需按索引迭代数组。如果只按元素进行迭代,则不能以类似于zip操作的方式组合流。首先,定义减法矩阵的外观。现在,我只定义相同大小的矩阵:
public static void subtract(int[] origin, int[] operand) {
if (origin.length != operand.length) throw new IllegalArgumentException("Array lengths must match");
//Make a new result, so as not to muck with the original array
return IntStream.range(0, origin.length).map(i -> origin[i] - operand[i]).toArray();
}
然后,生成差异是直接传入这些矩阵的问题,而流只是作为迭代两组元素的问题使用。因此,该任务也可以通过一个简单的香草for循环来完成。尽管如此:
int[] result = subtract(one, two);
我们还可以抽象上述逻辑,以允许更灵活的操作集:
public static int[] operate(int[] origin, int[] operand, IntBiFunction operation) {
if (origin.length != operand.length) throw new IllegalArgumentException("Array lengths must match");
return IntStream.range(0, origin.length)
.forEach(i -> result[i] = operation.apply(origin[i], operand[i]))
.toArray();
}
public static void subtract(int[] origin, int[] operand) {
//Producing result from each index matched element
return operate(origin, operand, (one, two) -> one - two);
}
在这里,我看到了使用任何与函数api相关的东西的更多优势
如果希望使用返回值IntStream
而不是int[]
,则可以,但会遇到必须按索引引用数组的原始问题。您确实可以推送它并提供任意数量的操作(IntBiFunction…operations
),但我认为您可能会使逻辑过于复杂。这有帮助吗?还是这个?