LambdaJ: why can't we apply operation in select clause?

208 Views Asked by At
select(list, having(on(Integer.class).intValue() % 2, equalTo(0)));

the code above throws exception.

2

There are 2 best solutions below

0
Peter Lawrey On BEST ANSWER

The % operation has to be evaluated before select() whereas what you want it to be evaluated for each entry. i.e. what you want is closures which is available in Java 8.

If you were using a loop you could write

for(int i: list)
    if(i % 2 == 0)
       // do something with i.

Java's syntax often makes using a loop the cleanest solution when ideally you should have a choice (its also a lot faster).

0
HellishHeat On

You'll want to define your own matcher:

Matcher<Integer> even = new Predicate<Integer>() {         
 public boolean apply(Integer item) {                 
 return item % 2 == 0;         
} };

Adapted from:http://code.google.com/p/lambdaj/wiki/LambdajFeatures