Home > Enterprise >  how to use java 8 stream in a loop and add results in a list
how to use java 8 stream in a loop and add results in a list

Time:10-05

I am using Java 8 stream in a loop, and the problem is that the final result is null. When I remove the loop, the final result is okay. And I guess the problem is with the collect part but I have no idea about what to use instead. So, could anyone help me with this? Thanks

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;
  }

CodePudding user response:

You don't need to combine a loop and a stream action, you can work wit only streams thanks to flatMap:

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());
  •  Tags:  
  • java
  • Related