我在循环中使用Java8流,问题是最终结果为空。当我删除循环时,最终结果是好的。我想问题是收集
部分,但我不知道该用什么来代替。所以,有人能帮我吗?谢谢
public List<Book> updateBooks(String libraryId) {
List<States> states = new ArrayList<>();
states.add(States.AVAILABLE);
states.add(States.BORROWED);
states.add(States.BLOCKED);
for (State state : states) {
books = getBooks(libraryId,state.getValue());
allBooks = books .getValues().stream().map(book -> {
Book bookInfo = new Book();
bookInfo.setId(book.getId());
bookInfo.setTitle(book.getTitle());
bookInfo.setState(book.getState());
bookInfo.setLinks(book.getLinks());
return pullRequestInfo;
}).collect(Collectors.toList());
}
return allBooks;
}
您不需要组合循环和流操作,您可以使用plitMap
只处理流:
List<States> states = new ArrayList<>();
states.add(States.AVAILABLE);
states.add(States.BORROWED);
states.add(States.BLOCKED);
return states.stream()
.flatMap(state -> getBooks(libraryId, state.getValue())
.getValues()
.stream()
)
.map(book -> {
Book bookInfo = new Book();
bookInfo.setId(book.getId());
bookInfo.setTitle(book.getTitle());
bookInfo.setState(book.getState());
bookInfo.setLinks(book.getLinks());
return bookInfo;
})
.collect(Collectors.toList());