Java内部类/闭包

发布于 2024-11-01 03:00:00 字数 326 浏览 10 评论 0原文

所以我有以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

千笙结 2024-11-08 03:00:00

实用方法怎么样?

public static <T> void addIfNotNull(Collection<T> col, T element){
    if(element != null){
        col.add(element);
    }
}

How about a utility method?

public static <T> void addIfNotNull(Collection<T> col, T element){
    if(element != null){
        col.add(element);
    }
}
旧伤还要旧人安 2024-11-08 03:00:00

您可以尝试Google Code中的Project LambdaJ,它的使用非常成熟 使用 Java 过滤闭包

根据条件

:根据给定条件过滤集合中的项目是一项非常常见的任务,使用 lambdaj 可以像以下示例一样简单:

List<Integer> biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));

定义如何过滤列表的条件表示为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:

List<Integer> biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));

The condition that defines how to filter the list is expressed as an hamcrest matcher.

Or you can wait for JDK 8 :-)

甚是思念 2024-11-08 03:00:00
List list = new ArrayList();

add(data.getA());
add(data.getB());
add(data.getC());

private add(Object o) {
    if (o != null) {
        list.add(o);
    }
}
List list = new ArrayList();

add(data.getA());
add(data.getB());
add(data.getC());

private add(Object o) {
    if (o != null) {
        list.add(o);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文