下面的代码将一个对象流拆分为1000块,在物化时对它们进行处理,并返回最后的对象总数。
在所有情况下,返回的数字都是正确的,除非流大小恰好是1。在流大小为1的情况下,返回的数字是0。
任何帮助都将不胜感激。在流中没有记录为0的情况下,我还必须黑掉返回调用。我也想解决这个问题。
AtomicInteger recordCounter = new AtomicInteger(0);
try (StreamEx<MyObject> stream = StreamEx.of(myObjects)) {
stream.groupRuns((prev, next) -> recordCounter.incrementAndGet() % 1000 != 0)
.forEach((chunk) ->
{
//... process each chunk
}
);
} catch(Exception e) {
throw new MyRuntimeException("Failure streaming...", e);
} finally {
myObjects.close();
}
return recordCounter.get() == 0 ? 0 : recordCounter.incrementAndGet();发布于 2017-10-10 14:24:57
最后,我使用了番石榴的Iterators.partition()将我的对象流分割成块:
MutableInt recordCounter = new MutableInt();
try {
Iterators.partition(myObjects.iterator(), 1000)
.forEachRemaining((chunk) -> {
//process each chunk
...
recordCounter.add(chunk.size());
});
} catch (Exception e) {
throw new MyRuntimeException("Failure streaming...", e);
} finally {
myObjects.close();
}
return recordCounter.getValue();发布于 2017-10-01 08:00:59
正如JavaDoc所说:
sameGroup -一种非干扰的无状态谓词,用于对属于同一组的元素返回true的相邻元素对。
谓词必须是无状态的,这不是您的情况。你在滥用这个方法,这就是为什么你不能得到预期的结果。它的工作非常接近您的期望,完全是偶然的,您不能依赖这种行为,它可能会在未来的StreamEx版本中发生变化。
发布于 2017-08-12 13:09:06
最初计数器用于知道何时分割块,并且不可靠地计数对象的总数。当流大小为0或1时,不执行groupRuns函数。
所以你需要另一种方法来计数物体。不只是使用forEach中的项,您可以返回处理过的chunk.size()和sum对象的数量。
AtomicInteger counter = new AtomicInteger(0);
try (StreamEx<MyObject> stream = StreamEx.of(myObjects)) {
return stream
.groupRuns((prev, next) -> counter.incrementAndGet() % 1000 != 0)
.mapToLong((chunk) -> {
//... process each chunk
return chunk.size();
})
.sum();
} catch(Exception e) {
throw new MyRuntimeException("Failure streaming...", e);
} finally {
myObjects.close();
}https://stackoverflow.com/questions/45649990
复制相似问题