StreamEx分组到列表中返回的记录数不正确 [英] StreamEx grouping into lists returns an incorrect number of records

查看:174
本文介绍了StreamEx分组到列表中返回的记录数不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将对象流拆分为1000个块,在物化时处理它们并返回最后的对象总数。

The following code splits a stream of objects into chunks of 1000, processes them on materialisation and returns the total number of objects at the end.

在所有情况下返回的数字是正确的,除非流大小恰好为1.如果流大小为1,则返回的数字为0.

In all cases the number returned is correct unless the stream size happens to be 1. In the case the stream size is 1, the number returned is 0.

任何帮助将不胜感激。如果流中没有记录为0,我也不得不破解回叫。我也想解决这个问题。

Any help would be greatly appreciated. I have also had to hack the return call in the case there are no records in the stream to be 0. I'd like to fix this too.

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();


推荐答案

最后我去了番石榴的 Iterators.partition()将我的对象流分割成块:

In the end I went with Guava's Iterators.partition() to split my stream of objects into chunks:

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();

这篇关于StreamEx分组到列表中返回的记录数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆