Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

List<Integer> list = Lists.newArrayList(1,2,3);

List<Integer> list2 = null;

//throws nullPointer

list.addAll(list2);

//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

1 Answer

0 votes
by (46k points)

For Java 8 you can try, 

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

But I prefer ternary expression. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...