Search code examples
javacollectionsjava-8

Is there a Java 8 syntax for collections.addAll() to work with null parameters?


List<Integer> list = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = null;
// throws NullPointerException
list.addAll(list2);

// using a check here    
if (list2 != null) {
    list.addAll(list2);   
}

Is there a Java 8 way of doing it simple in one line?

This is one I have, but I actually don't need the boolean created:

boolean added = list2 != null ? list1.addAll(list2) : false;

Solution

  • If you specifically want a Java 8 way, you can do

    Optional.ofNullable(list2).ifPresent(list::addAll);
    

    But I don't think it wins much over the ternary expression.