java传递流顺序的方法引用

3gtaxfhh  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(325)

我有一个处理器类,它接受在流上运行的任意 predicate ,还有一个用于排序的字段。我的处理器类:

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;
    }
}

我不能让这个工作和铸造一个比较也失败。解决方案不必是比较器,只要排序就行。有人知道怎么解决这个问题吗?

camsedfj

camsedfj1#

系统的一般约束 Function 的参数 Comparator#comparing<T,U extends Comparable<? super U>> ,这意味着函数必须返回扩展的内容 Comparable<…> . 将您的功能从 Function<Transaction, Object>Function<Transaction, Comparable<…>> 你应该能做到 .sorted(Comparator.comparing(order)) .
唯一的要求是 Transaction#getCategory 方法返回 Comparable (字符串、数字、实现的自定义类型) Comparable<YourType> ).

相关问题