0

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;
  }
Tindona
  • 430
  • 1
  • 16
  • 3
    Does this answer your question? [How to add elements of a Java8 stream into an existing List](https://stackoverflow.com/questions/22753755/how-to-add-elements-of-a-java8-stream-into-an-existing-list) – peterulb Oct 05 '22 at 08:21
  • 3
    Could you please describe the purpose of the return value? What is it supposed to contain? – deHaar Oct 05 '22 at 08:21
  • 3
    Note that every time you call `collect`, you assign a new list to `allBooks`. So it contains the last loop iteration`s result – peterulb Oct 05 '22 at 08:22

1 Answers1

2

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());
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20