Bilgin Silahtaroğlu
Bilgin Silahtaroğlu

Reputation: 71

How to do If-or operation in lambda

I get all book's information to one list and filter them with a keyword.

List<Book> books = bookService.getAllBooks();

List<Book> filteredBooks = books.stream().filter(b-> b.getName().contains(keyword) || b.getDescription().contains(keyword))

But, b.getDescription() can return null, so I got null pointer exception.

How can I do an operation in filter like b.getName() OR IF !b.getDescription().isEmpty b.getDescription()?

Upvotes: 1

Views: 41

Answers (1)

Nicholas K
Nicholas K

Reputation: 15423

Use:

List<Book> filteredBooks = books.stream()
                                .filter(b-> b.getName().contains(keyword) ||
                                            (b.getDescription() != null && b.getDescription().contains(keyword)));

Upvotes: 1

Related Questions