java - operators in predicate as argument in lambda expression -
i need use predicate argument in lambda expression. tried example code seeing compiler error. see compiler treating same predicate differently different arguments. predicate arguments n -> true , n -> false
works n -> n%4 == 0
doesn't work.
the compiler error is:
the operator % undefined argument type(s) object, int
i fixed (see replacement code below) asking should have fix , why? not sure if missing basic.
here complete code:
import java.util.arraylist; import java.util.list; import java.util.function.predicate; public class predicateasargumentinlambdaexpression { public static int add(list<integer> numlist, predicate predicate) { int sum = 0; (int number : numlist) { if (predicate.test(number)) { sum += number; } } return sum; } public static void main(string args[]){ list<integer> numlist = new arraylist<integer>(); numlist.add(new integer(10)); numlist.add(new integer(20)); numlist.add(new integer(30)); numlist.add(new integer(40)); numlist.add(new integer(50)); system.out.println("add everything: "+add(numlist, n -> true)); system.out.println("add nothing: "+add(numlist, n -> false)); // system.out.println("add less 25: "+add(numlist, n -> n < 25)); compiler says: operator < undefined argument type(s) object, int system.out.println("add less 25: "+add(numlist, n -> integer.valueof((int)n) < integer.valueof("25"))); // system.out.println("add 4 multiples: "+add(numlist, n -> n % 4 == 0)); //compiler says: operator % undefined argument type(s) object, int system.out.println("add 4 multiples: "+add(numlist, n -> integer.valueof((int)n) % integer.valueof("4")==0)); } }
commented out code what's not working , line below each replacement code. code works , expected expecting commented out code should have worked! what's isn't ok predicate in java.util.function.predicate here?. please provide link specification page if find answer in.
what happening you're using raw java.util.function.predicate
, on test()
method like:
public void test(object o) { ... }
this why compile-time error: argument type object
, numeric operators (<
, >
) not applicable type object
.
however, if use generic java.util.function.predicate
type-parameter of integer
, test()
method like:
public void test(integer i) { ... }
in case, numeric operators (>
, <
) valid provided argument type (integer
) , there's no need of casts.
also, i've taken advantage of stream api in java8 shorten method implementation:
public static int add(list<integer> numlist, predicate<integer> predicate) { return numlist.stream().filter(predicate).maptoint(i -> i).sum(); }
having method implemented this, these statements valid:
system.out.println("add everything: "+add(numlist, n -> true)); system.out.println("add nothing: "+add(numlist, n -> false)); system.out.println("add less 25: "+add(numlist, n -> n < 25)); system.out.println("add 4 multiples: "+add(numlist, n -> n % 4 == 0));
Comments
Post a Comment