I have a result of type User as follows:
List<User> result = (getting values from db)
the properties of class User that I need are:
private Integer id,
private String name,
private List<Books> books = new ArrayList<>();
etc.
And Class Books has a field Id to.
Given that I have the user Id, and the books Id. I would like to access the other results inside the array book, for that book id.
So I need to -> give the result variable a specific userId, and access books property for that user, then give a bookId, and access book properties for that book id, in that user. I tried using java streams:
List<BooksDetails> userBook = result.stream()
.filter(user -> user.getId() == 1)
.collect(Collectors.toList())
.get(0)
.getBooks()
.stream()
.filter(book -> book.getId() == 2)
.collect(Collectors.toList())
.get(0)
.getBooksDetails();
But sometimes I get index out of bound error when accessing get(0) element. And it seems there might be a cleaner solution to this. What approaches can I use to accessing nested properties by giving the associated id's in a list? OR would I have to convert it to a nested map instead?