Is there a construct in java that does something like this(here implemented in python):
[] = [item for item in oldList if item.getInt() > 5]
Today I'm using something like:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.add(item);
}
}
And to me the first way looks a bit smarter.
Java 7 might or might not implement closures and hence support functionality like this, but currently it doesn't, so on the Java VM you have the options to do it in Groovy, Scala or Clojure (possible others, too), but in java you can only get close to that by using helpers like Guava's Collections2.filter().
JDK 7 sample code:
findItemsLargerThan(List<Integer> l, int what){
return filter(boolean(Integer x) { x > what }, l);
}
findItemsLargerThan(Arrays.asList(1,2,5,6,9), 5)
Groovy sample code:
Arrays.asList(1,2,5,6,9).findAll{ it > 5}
Guava Sample Code:
Collections2.filter(Arrays.asList(1, 2, 5, 6, 9),
new Predicate<Integer>(){
@Override
public boolean apply(final Integer input){
return input.intValue() > 5;
}
}
);
Scala sample code (thanks Bolo):
Array(1, 2, 5, 6, 9) filter (x => x > 5)
You can give a look at lambdaj. There is a select method you can use with a hamcrest condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With