在方法中使用不同的 getter

Using different getters in a method

给出如下方法

public int calcSum(List<MyClass> items) {
    return items.stream()
                .mapToInt(i -> i.getHeight())
                .sum();
}

使用不同的 getter 有什么选择,我可以将它们传递给方法的参数,这样我就不必用 getWeight() 重复相同的 return 语句?

我正在考虑使用一种不同的方法 return 吸气剂(如果可能的话),但我在考虑一个好的实现时遇到了麻烦。 感谢您的帮助!

传入一个ToIntFunction<T>作为参数:

public <T> int calcSum(List<T> items, ToIntFunction<? super T> fn) {
    return items.stream()
                .mapToInt(fn)
                .sum();
}

// Example invocations:
int heightSum = calcSum(items, MyClass::getHeight);
int weightSum = calcSum(items, MyClass::getWeight);

<? super T> 是一个 bounded wildcard(具体来说是一个 lower-bounded 通配符 )。它只是让 API 更灵活一点。比如因为通配符,可以调用:

ToIntFunction<Object> constantValue = a -> 1;
int count = calcSum(items, constantValue);

因为constantValue接受任何Object,它也可以接受MyClass个实例。

没有边界,您将无法传入 ToIntFunction<Object>:对于不同的列表元素类型,您需要有单独的实例:

ToIntFunction<MyClass> constantValueForMyClass = a -> 1;
ToIntFunction<MyOtherClass> constantValueForMyOtherClass = a -> 1;
ToIntFunction<YetAnotherClass> constantValueForYetAnotherClass = a -> 1;
// ...

这是乏味和重复的。