Ged*_*bel 3 java iterator mahout java-8
请考虑以下代码段:
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;
}
Run Code Online (Sandbox Code Playgroud)
break
或者return
不在这里工作.我能做什么?
提前停止迭代的唯一方法是抛出异常.不建议使用控制流的异常,因此我将使用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());
}
Run Code Online (Sandbox Code Playgroud)
如果无法更改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());
}
Run Code Online (Sandbox Code Playgroud)