Is it possible to do this using Predicate interface.
I have a client class that utilizes functions provided by a MathUtility class. Whatever the Mathmatical operation it should happen only within the MathUtility class.
//in client
MathUtility.sum(listOfInts, (Integer i)->{return (i<3);});
//in utility
class MathUtility<T extends Number> {
public static <T extends Number> T sumWithCondition(List<T> numbers, Predicate<T> condition) {
return numbers.parallelStream()
.filter(condition)
.map(i -> i)
.reduce(0, T::sum); //compile time error
}
public static <T extends Number> T avgWithCondition(List<T> numbers, Predicate<T> condition) {
//another function
}
//lot many functions go here
}
Right now it fails with this error - The method reduce(T, BinaryOperator<T>) in the type Stream<T> is not applicable for the arguments (int, T::sum)
Note: I do not want to write sum functions for different Number types
As Aaron Davis stated in a comment above, you can pass the reduction parameters to the method itself.
An example would be:
Number
to be summed, Since theNumber
class has no static sum method.identity
with type ofT extends Number
,0
is an concrete type of Integer and does not compatible with type ofT
.Possible Solution
you can make which actual type of
Number
to be summed later, for example:OR you can make which actual type of
Number
to be summed ahead, when using this style you are free to take type of actualNumber
to every sum to be called, one the other hand, you can reuse it without taking any confused parameters and which is exactly what you want,for example:MathUtility
SumOp
A much simpler approach I tired is this.
The point to be noted is that the addition logic doesn't happen at the invoking side instead only within the MathUtility. The downside here is that you have to create Addition classes for every Number type you want the + operation.
The answer is yes, that should be possible. The you defined is not known to have the method "sum", therefore the compiler complains. Try to define
(I haven't tried this code in IDE but this should do the trick)