我有一个处理器类,它接受在流上运行的任意谓词,还有一个用于排序的字段。我的处理器类:
import com.example.vm.domain.Transaction;
import lombok.Builder;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Builder
public class Processor {
private Collection<Predicate<Transaction>> predicates;
public List<Transaction> process(List<Transaction> transactions) {
return process(transactions, TransactionFields.CATEGORY.getExtractor());
}
public List<Transaction> process(List<Transaction> transactions, Function<Transaction, Object> order) {
if (predicates == null) {
return transactions;
}
if (order == null) {
return transactions.stream()
.parallel()
.filter(predicates.stream().reduce(p -> true, Predicate::and))
.collect(Collectors.toList());
} else {
return transactions.stream()
.parallel()
.filter(predicates.stream().reduce(p -> true, Predicate::and))
.sorted(Comparator.comparing(Transaction::getCategory))
.collect(Collectors.toList());
}
}
}
这很好,但我希望Comparator.comparing(Transaction::getCategory)
是一个参数,这样
.sorted(Comparator.comparing(Transaction::getCategory))
变成这个
.sorted(Comparator.comparing(order))
过载呼叫:
process(transactions, TransactionFields.CATEGORY.getExtractor());
来自枚举以返回提取器字段:
import com.example.vm.domain.Transaction;
import java.util.function.Function;
public enum TransactionFields {
CATEGORY("category", t -> t.getCategory());
private String name;
private Function<Transaction, Object> extractor;
private TransactionFields(String name, Function<Transaction, Object> extractor) {
this.name = name;
this.extractor = extractor;
}
public Function<Transaction, Object> getExtractor() {
return extractor;
}
}
我无法实现这一点,并且向Comparator进行选角也会失败。解决方案不一定是Comparator,只要它排序即可。有人知道怎么解决这个问题吗?
Comparator#comparing
的Function
参数的通用约束是<T,U extends Comparable<? super U>>
,这意味着函数必须返回扩展Comparable<…>
的内容。将您的函数从Function<Transaction, Object>
更改为Function<Transaction, Comparable<…>>
,您应该能够执行.sorted(Comparator.comparing(order))
。
唯一的要求是Transaction#getCategory
方法返回Comparable
(String、number、实现Comparable<YourType>
的自定义类型(。