给出以下方法
public int calcSum(List<MyClass> items) {
return items.stream()
.mapToInt(i -> i.getHeight())
.sum();
}
Run Code Online (Sandbox Code Playgroud)
我可以使用哪些可以在方法参数中传递的不同getter的选项是什么,这样我就不必getWeight()例如重复相同的return语句?
我当时在考虑使用一种可能会返回吸气剂的其他方法(如果可能的话),但是我很难想到一个好的实现方法。谢谢您的帮助!
And*_*ner 10
传递a 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);
Run Code Online (Sandbox Code Playgroud)
的<? super T>是AA 界通配符(具体为低界通配符)。它只是使API更加灵活。例如,由于通配符,您可以调用:
ToIntFunction<Object> constantValue = a -> 1;
int count = calcSum(items, constantValue);
Run Code Online (Sandbox Code Playgroud)
因为constantValue接受any Object,所以它也可以接受MyClass实例。
没有界限,您将无法传递ToIntFunction<Object>:对于不同的列表元素类型,您需要具有单独的实例:
ToIntFunction<MyClass> constantValueForMyClass = a -> 1;
ToIntFunction<MyOtherClass> constantValueForMyOtherClass = a -> 1;
ToIntFunction<YetAnotherClass> constantValueForYetAnotherClass = a -> 1;
// ...
Run Code Online (Sandbox Code Playgroud)
这是乏味且重复的。