如何在lambda中执行if-or操作

时间:2019-05-11 17:39:38

标签: java lambda

我将所有书籍的信息都收集到一个列表中,并使用关键字对其进行过滤。

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

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

但是b.getDescription()可以返回null,所以我得到了null指针异常。

如何在b.getName() OR IF !b.getDescription().isEmpty b.getDescription()之类的过滤器中进行操作?

1 个答案:

答案 0 :(得分:1)

使用:

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