我有简单的Book
类,其中包含类似[]的字段>
private String ISBN; private String title; private String author;
我想创建搜索查询,将
BookDto
作为条件,并将所有不可为空的字段与我的List<Book>
的元素进行比较。所以我写了一些简单的Predicates
private Predicate<Book> matchingAuthor(Book another) { return book -> book.getAuthor() != null && book.getAuthor().equals(another.getAuthor()); } private Predicate<Book> matchingTitle(Book another) { return book -> book.getTitle() != null && book.getTitle().equals(another.getTitle()); } private Predicate<Book> matchingISBN(Book another) { return book -> book.getISBN() != null && book.getISBN().equals(another.getISBN()); }
而且我想拥有1个可以处理所有逻辑的搜索方法
private List<BookDto> findMatchingBooks(BookDto criteria) { return books.stream().map(BookConverter::toEntity).filter(this::matchingBook).map(BookConverter::toDto).collect(Collectors.toList()); }
但是这种逻辑很难看……而且无法按我想要的方式工作。
private Predicate<Book> matchingBook(Book criteria) { if(criteria.getISBN() != null) { return matchingISBN(criteria); } else if(criteria.getISBN() == null && criteria.getTitle() == null && criteria.getAuthor() != null) { return matchingAuthor(criteria); } else if(criteria.getISBN() == null && criteria.getTitle() != null && criteria.getAuthor() != null) { return matchingAuthor(criteria) && matchingTitle(criteria); } }
[前两个
if/else
可以说很好(难看,但是正在工作),第三个正在引起]
二进制运算符'&&'的错误操作数类型第一类:谓词第二种类型:谓词
问题是,我如何实现这一目标?
我有一个简单的Book类,其中包含诸如私有String ISBN之类的字段;私有字符串标题;私人String作者;我想创建搜索查询,将BookDto作为标准,然后...
您需要使用and
组合谓词:
您必须使用return matchingAuthor(criteria).and(matchingTitle(criteria));
来组合Predicate::and
:
Insted of