Gra*_*uin 6 python java collections closures
在java中是否有一个像这样的结构(这里用python实现):
[] = [item for item in oldList if item.getInt() > 5]
Run Code Online (Sandbox Code Playgroud)
今天我用的是:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.add(item);
}
}
Run Code Online (Sandbox Code Playgroud)
对我而言,第一种方式看起来更聪明.
Java 7 可能会也可能不会实现闭包,因此支持这样的功能,但目前它没有,所以在Java VM上你可以选择在Groovy,Scala或Clojure中完成它(也可能是其他的),但是在Java中你只能通过使用像Guava的Collections2.filter()这样的助手来接近它.
JDK 7示例代码:
findItemsLargerThan(List<Integer> l, int what){
return filter(boolean(Integer x) { x > what }, l);
}
findItemsLargerThan(Arrays.asList(1,2,5,6,9), 5)
Run Code Online (Sandbox Code Playgroud)
Groovy示例代码:
Arrays.asList(1,2,5,6,9).findAll{ it > 5}
Run Code Online (Sandbox Code Playgroud)
番石榴样本代码:
Collections2.filter(Arrays.asList(1, 2, 5, 6, 9),
new Predicate<Integer>(){
@Override
public boolean apply(final Integer input){
return input.intValue() > 5;
}
}
);
Run Code Online (Sandbox Code Playgroud)
Scala示例代码(感谢Bolo):
Array(1, 2, 5, 6, 9) filter (x => x > 5)
Run Code Online (Sandbox Code Playgroud)