Java 7 may or may not implement closures and therefore support functions such as this, but this is not the case at present, so in a Java virtual machine you can do this in Groovy , Scala or Clojure (others are possible), but in java you can only approach this with helpers such as Guava Collections2.filter () .
Sample JDK 7 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)
Sean Patrick Floyd
source share