我有两个对象,使用一个函数列表中的每个字段,对每个字段使用不同的功能来逐字段进行比较。

目标:使用功能列表调用compare(NeedCompare n1, NeedCompare n2)并获取BigDecimal value = compareAmount(NeedCompare needCompare1, NeedCompare needCompare2).add(compareValue(NeedCompare needCompare1, NeedCompare needCompare2).add(compareName(NeedCompare needCompare1, NeedCompare needCompare2).add(compareCategory(NeedCompare needCompare1, NeedCompare needCompare2)))))
使它与流将是完美的。

public class NeedCompare {
private BigDecimal category;
private String name;
private BigDecimal value;
private BigDecimal amount;

// The list is wrong and I don't know how to organize it
private List<Function<BigDecimal, NeedCompare>> functions = Arrays.asList(
        (needCompare1, needCompare2) -> compareCategory(needCompare1, needCompare2),
        (needCompare1, needCompare2) -> compareName(needCompare1, needCompare2),
        (needCompare1, needCompare2) -> compareValue(needCompare1, needCompare2),
        (needCompare1, needCompare2) -> compareAmount(needCompare1, needCompare2)

);

public BigDecimal compare(NeedCompare n1, NeedCompare n2) {
    //The method is broken. I need to return a sum of the results of the functions
    return functions.stream().map(function -> function(n1, n2)).reduce(BigDecimal.ZERO, BigDecimal::add);
}

private BigDecimal compareAmount(NeedCompare needCompare1, NeedCompare needCompare2) {
    // Complex function to compare category of NeedCompare
    return needCompare1.getCategory().equals(needCompare2.getCategory()) ? BigDecimal.ZERO : BigDecimal.ONE;
}

private BigDecimal compareValue(NeedCompare needCompare1, NeedCompare needCompare2) {
    // Complex function to compare name of NeedCompare
    return needCompare1.getName().equals(needCompare2.getName()) ? BigDecimal.ZERO : BigDecimal.ONE;
}

private BigDecimal compareName(NeedCompare needCompare1, NeedCompare needCompare2) {
    // Complex function to compare value of NeedCompare
    return needCompare1.getValue().equals(needCompare2.getValue()) ? BigDecimal.ZERO : BigDecimal.ONE;
}

private BigDecimal compareCategory(NeedCompare needCompare1, NeedCompare needCompare2) {
    // Complex function to compare amount of NeedCompare
    return needCompare1.getAmount().equals(needCompare2.getAmount()) ? BigDecimal.ZERO : BigDecimal.ONE;
}
// Getters and setters ...

最佳答案

您拥有的函数有两个参数,因此它们是BiFunction<NeedCompare, NeedCompare, BigDecimal>(第一个是参数的类型,返回/目标类型是最后一个)。所以你有private List<BiFunction<NeedCompare, NeedCompare, BigDecimal>> functions

另外,您可以使用方法引用而不是lambdas来使列表更容易阅读:

private List<BiFunction<NeedCompare, NeedCompare, BigDecimal>> functions
    = Arrays.asList(this::compareCategory, this::compareName,
        this::compareValue, this::compareAmount);

10-06 07:01