为流顺序传递方法引用

Passing Method References For Stream Order

我有一个处理器 class 接受任意谓词 运行 在流上,加上一个用于排序的字段。我的处理器 class:

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());

来自枚举到 return 提取器字段:

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#comparingFunction 参数的一般约束是 <T,U extends Comparable<? super U>>,这意味着函数必须 return 扩展 Comparable<…> 的东西。将您的功能从 Function<Transaction, Object> 更改为 Function<Transaction, Comparable<…>> 并且您应该能够执行 .sorted(Comparator.comparing(order)).

唯一的要求是您的 Transaction#getCategory 方法 return 是 Comparable 的东西(字符串、数字、实现 Comparable<YourType> 的自定义类型)。