假设我有一个带有两个谓词的方法:(为了清晰起见,进行了简化)
public List<Data> getData(List<OtherData> otherData, String value, String otherValue) {
Predicate<OtherData> predicate1 = otherData -> otherData.getValue().equals(value))
Predicate<OtherData> predicate2 = otherData -> otherData.getOtherValue().equals(otherValue))
return otherData.stream()
.filter(predicate1.and(predicate2))
.map(otherData -> Data.of(otherData))
.collect(Collectors.toList())
}
但是假设我想更改此代码,以便根据 String value
的可用性动态创建和使用谓词和String otherValue
- 无论何时not null
.
我已经使用 javax.persistence.criteria.CriteriaBuilder
看到了这种方法和javax.persistence.criteria.CriteriaQuery
,创建 List<Predicate>
并使用一些 ifology 来填充此列表,例如
列出谓词; 如果(值!=空){ predicates.add(//这里的谓词逻辑); }
稍后在 CriteriaQuery.query.where()
中使用它们
但这是与持久性相关的东西,我想在非持久性上下文中执行它(如果可能的话,没有ifology)
这可能吗?
最佳答案
您可以通过以下方式实现谓词: value == null || elementValue.equals(值)。
Predicate<OtherData> valueNull = v -> Objects.isNull(value);
Predicate<OtherData> predicate1 = valueNull.or(otherData -> otherData.getValue().equals(value)))
关于java - 当满足特定条件时,是否可以在 Java Stream 中使用谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70955807/