编程语言
首页 > 编程语言> > 使用Java8中断/停止forEachRemaning

使用Java8中断/停止forEachRemaning

作者:互联网

请考虑以下代码段:

private List<User> getUsers() throws TasteException {
        final int MAX_USERS = 100;
        List<User> userList = new ArrayList<>(MAX_USERS);
        dataModel.getUserIDs().forEachRemaining(userId -> {
            if (userList.size() == 100) {
                // stop
            }
            userList.add(new User(userId));
        });
        return userList;
    }

休息或返回在这里不起作用.我能做什么?

解决方法:

提前停止迭代的唯一方法是抛出异常.不建议使用控制流的异常,因此我将使用Stream.limit,.map和.collect:

private List<User> getUsers() throws TasteException {
  final int MAX_USERS = 100;
  return dataModel.getUserIDs()
                  .stream()
                  .limit(MAX_USERS)
                  .map(userId -> new User(userId))
                  .collect(Collectors.toList());
}

如果无法更改getUserIDs以返回Collection,则可以先转换为Spliterator:

private List<User> getUsers() throws TasteException {
  final int MAX_USERS = 10;
  return StreamSupport.stream(Spliterators.spliteratorUnknownSize(dataModel.getUserIDs(), 0), false)
                      .limit(MAX_USERS)
                      .map(userId -> new User(userId))
                      .collect(Collectors.toList());
}

标签:java,iterator,java-8,mahout
来源: https://codeday.me/bug/20190717/1491144.html