Java内部类/闭包
所以我有以下内容:
Object a = data.getA();
Object b = data.getB();
Object c = data.getC();
// and so on
这些对象是从 API 调用中检索的,并且可能为 null。我想将这些对象放入列表中,但前提是它们不为空。
我可以写一堆行: if(a!=null) {myList.add(a}
等等。但我感觉有一种更优雅的方法可以避免每次都进行 null 检查(除了创建一个辅助方法来执行此操作),
例如,我可以创建一个 Java 闭包。
So I have the following:
Object a = data.getA();
Object b = data.getB();
Object c = data.getC();
// and so on
These objects are retrieved from API calls and may be null. I want to put these objects into a List, but only if they are not null.
I could write a bunch of lines: if(a!=null) {myList.add(a}
and so on. But I have the feeling that there is a more elegant way that would avoid having to do the null check each time (aside from creating a helper method to do this).
With javascript, for instance, I could create a closure. Any ideas for Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实用方法怎么样?
How about a utility method?
您可以尝试Google Code中的Project LambdaJ,它的使用非常成熟 使用 Java 过滤闭包
根据条件
:根据给定条件过滤集合中的项目是一项非常常见的任务,使用 lambdaj 可以像以下示例一样简单:
定义如何过滤列表的条件表示为hamcrest 匹配器。
或者你可以等待 JDK 8 :-)
You could try Project LambdaJ in Google Code, it is very mature in the use of closures with Java
Filtering on a condition:
To filter the items of a collection on a given condition is a very common task and using lambdaj can be as easy as in the following example:
The condition that defines how to filter the list is expressed as an hamcrest matcher.
Or you can wait for JDK 8 :-)
你可以使用 Maybe 概念: http://www.natpryce.com/articles/000776.html< /a>
you coud use a Maybe concept: http://www.natpryce.com/articles/000776.html