开发者

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 o开发者_开发知识库bjects 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);
    }
}


you coud use a Maybe concept: http://www.natpryce.com/articles/000776.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜