我刚刚开始同时学习Java8流和Apache共用Math3,并寻找失去的机会来简化我的解决方案,以比较实例是否相等。考虑一下这个Math3 RealVector
RealVector testArrayRealVector =
new ArrayRealVector(new double [] {1d, 2d, 3d});并将这个包含装箱双倍的成员变量,再加上它的这个副本作为数组列表集合:
private final Double [] m_ADoubleArray = {13d, 14d, 15d};
private final Collection<Double> m_CollectionArrayList =
new ArrayList<>(Arrays.asList(m_ADoubleArray));下面是我在JUnit类(这里的全部要点)中使用码根质子包比较这些函数样式的最佳方法,因为我在Streams库中找不到zip。在我看来,这真的是巴洛克式的,我想知道我是否错过了让这个变得更短、更快、更简单、更好的方法,因为我才刚开始学习这些东西,却不知道多少。
// Make a stream out of the RealVector:
DoubleStream testArrayRealVectorStream =
Arrays.stream(testArrayRealVector.toArray());
// Check the type of that Stream
assertTrue("java.util.stream.DoublePipeline$Head" ==
testArrayRealVectorStream.getClass().getTypeName());
// Use up the stream:
assertEquals(3, testArrayRealVectorStream.count());
// Old one is used up; make another:
testArrayRealVectorStream = Arrays.stream(testArrayRealVector.toArray());
// Make a new stream from the member-var arrayList;
// do arithmetic on the copy, leaving the original unmodified:
Stream<Double> collectionStream = getFreshMemberVarStream();
// Use up the stream:
assertEquals(3, collectionStream.count());
// Stream is now used up; make new one:
collectionStream = getFreshMemberVarStream();
// Doesn't seem to be any way to use zip on the real array vector
// without boxing it.
Stream<Double> arrayRealVectorStreamBoxed =
testArrayRealVectorStream.boxed();
assertTrue(zip(
collectionStream,
arrayRealVectorStreamBoxed,
(l, r) -> Math.abs(l - r) < DELTA)
.reduce(true, (a, b) -> a && b));哪里
private Stream<Double> getFreshMemberVarStream() {
return m_CollectionArrayList
.stream()
.map(x -> x - 12.0);
}发布于 2015-08-21 15:01:20
看来你正不惜一切代价在Stream上保释。
如果我没听错你的话
double[] array1=testArrayRealVector.toArray();
Double[] m_ADoubleArray = {13d, 14d, 15d};作为起点。然后,您可以做的第一件事是验证这些数组的长度:
assertTrue(array1.length==m_ADoubleArray.length);
assertEquals(3, array1.length);将数组封装到流中并调用count()是没有意义的,当然,更不用说将数组包装到集合中以调用它上的stream().count()。注意,如果您的起点是Collection,那么调用size()也可以。
考虑到您已经验证了长度,您可以简单地
IntStream.range(0, 3).forEach(ix->assertEquals(m_ADoubleArray[ix]-12, array1[ix], DELTA));若要比较数组的元素,请执行以下操作。
或者当您想将算术作为一个函数应用时:
// keep the size check as above as the length won’t change
IntToDoubleFunction f=ix -> m_ADoubleArray[ix]-12;
IntStream.range(0, 3).forEach(ix -> assertEquals(f.applyAsDouble(ix), array1[ix], DELTA));注意,您还可以使用
double[] array2=Arrays.stream(m_ADoubleArray).mapToDouble(d -> d-12).toArray();并比较与上面类似的数组:
IntStream.range(0, 3).forEach(ix -> assertEquals(array1[ix], array2[ix], DELTA));或者仅仅是使用
assertArrayEquals(array1, array2, DELTA);与现在一样,这两个数组具有相同的类型。
不要考虑保存中间结果的临时三元素数组。所有其他尝试都会消耗更多的内存…。
https://stackoverflow.com/questions/32142260
复制相似问题