function - Generic method to perform a map-reduce operation. (Java-8) -
how overload function generic parameter in java 8?
public class test<t> { list<t> list = new arraylist<>(); public int sum(function<t, integer> function) { return list.stream().map(function).reduce(integer::sum).get(); } public double sum(function<t, double> function) { return list.stream().map(function).reduce(double::sum).get(); } }
error: java: name clash: sum(java.util.function.function<t,java.lang.double>) , sum(java.util.function.function<t,java.lang.integer>) have same erasure
the example present in question has got nothing java 8 , how generics work in java. function<t, integer> function
, function<t, double> function
go through type-erasure when compiled , transformed function
. rule of thumb method overloading have different number, type or sequence of parameters. since both methods transform take function
argument, compiler complains it.
that being said, srborlongan has provided 1 way resolve issue. problem solution have keep modifying test
class each , every type of operation (addition,subtraction,etc) on different types (integer,double, etc). alternate solution use method overriding
instead of method overloading
:
change test
class bit follows :
public abstract class test<i,o extends number> { list<i> list = new arraylist<>(); public o performoperation(function<i,o> function) { return list.stream().map(function).reduce((a,b)->operation(a,b)).get(); } public void add(i i) { list.add(i); } public abstract o operation(o a,o b); }
create subclass of test
add 2 integer
s.
public class mapstringtointaddtionoperation extends test<string,integer> { @override public integer operation(integer a,integer b) { return a+b; } }
client code can use above code follows :
public static void main(string []args) { test<string,integer> test = new mapstringtointaddtionoperation(); test.add("1"); test.add("2"); system.out.println(test.performoperation(integer::parseint)); }
the advantage of using approach test
class in line open-closed
principle. add new operation such multiplication, have add new subclass of test
, override
operation
method multiply 2 numbers. club decorator pattern , can minimize number of sub-classes have create.
note example in answer indicative. there lot of areas of improvement (such make test
functional interface instead of abstract class) beyond scope of question.
Comments
Post a Comment