Java 8 list processing – add elements conditionally

You could try to check the return value of addAll. It will return true whenever the list has been modified, so try this:

List<Object> list = new ArrayList<>();
// ret unused, otherwise it doesn't compile
boolean ret = list.addAll(method1())
    || list.addAll(method2()) 
    || list.addAll(method3())
    || list.addAll(method4())
    || list.addAll(method5())
    || list.addAll(method6());
return list;

Because of lazy evaluation, the first addAll operation that added at least one element will prevent the rest from bein called. I like the fact that “||” expresses the intent quite well.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)