简体   繁体   中英

Java inner class / closure

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?

How about a utility method?

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

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 :-)

List list = new ArrayList();

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

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

您可以使用Maybe概念: http : //www.natpryce.com/articles/000776.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM