![](/img/trans.png)
[英]get all matching non null elements if all the conditions are given in predicate
[英]Predicate all non null fields
我有简单的Book
class,其中包含以下字段
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
可以说是好的(丑陋但有效),第三个是导致
二元运算符'&&'的错误操作数类型第一种类型:谓词第二种类型:谓词
问题是,我怎样才能做到这一点?
您需要使用and
组合您的谓词:
return matchingAuthor(criteria).and(matchingTitle(criteria));
返回一个组合谓词,该谓词表示此谓词与另一个谓词的短路逻辑与。
您必须使用Predicate::and
来组合Predicates
:
return matchingAuthor(criteria).and(matchingTitle(criteria));
default Predicate<T> and(Predicate<? super T> other)
:
返回一个组合谓词,该谓词表示此谓词与另一个谓词的短路逻辑与。 在评估组合谓词时,如果该谓词为假,则不评估另一个谓词。 在评估任一谓词期间抛出的任何异常都将转发给调用者; 如果此谓词的评估引发异常,则不会评估另一个谓词。
安装在
return matchingAuthor(criteria) && matchingTitle(criteria);
去做
return matchingAuthor(criteria).and(matchingTitle(criteria));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.