Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 528
brain storm Avatar asked Oct 23 '25 17:10

brain storm


1 Answers

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.

like image 137
Misha Avatar answered Oct 26 '25 06:10

Misha