0

Is there a short and efficient way to add object to a list with null check?

Book book = new Book();
if (CollectionUtils.isNotEmpty(library.getBooks())) {
        library.getBooks().add(book);
} else {
        library.setBooks(Collections.singletonList(book));
}
12
  • 1
    Why don't initialize the collection inside the library object? Libraries can be empty. Commented Sep 25, 2018 at 18:59
  • CollectionUtils isn't for java 8 Commented Sep 25, 2018 at 19:01
  • @Cristiano this is the API, I cannot change it Commented Sep 25, 2018 at 19:01
  • 1
    @HadiJ library.getBooks() does not return an Optional Commented Sep 25, 2018 at 19:25
  • 1
    Is this your homework for class? Also making something work in one line of code; I use to do that until debugging was so painful and the code was complicated to read. Since then I break down my functionality into multiple lines for understandably as well as debugging. Using empty list if no list exist is what I would do. I think your question is confusing. why are you needing to check if your books are empty? Should it not matter if their are already books before you add more books? Commented Sep 25, 2018 at 19:50

1 Answer 1

4

I absolutely dislike the fact that your List could contain null, what is the point of that anyway? Why don't you refactor and return an empty one instead. Assuming that you cannot change that (please double check if you can), don't do it in a single line, just because it's fancy - it will be very unreadable in this particular case. Besides, I am strongly against these helper methods like CollectionsUtils or StringUtils, etc - that only make reading the code worse; not saying for all of them though (guava has some that I really like and use)

Instead, refactor this one to a simpler, more pleasant to look at method:

List<Book> books = library.getBooks();
if(books != null && !books.isEmpty()) {
     books.add(book);   
} else {
     library.setBooks(Collections.singletonList(book));    
}

How many seconds did it take you to understand this logic? As, for example opposed, to the other answer here (nothing personal, you made an excellent point).

But this still raises some questions for me personally. Why not move this entire logic to the Library class? What if you want later to add another book to a library? Because you have used Collections.singletonList which is immutable, you will not be able to.

Sign up to request clarification or add additional context in comments.

5 Comments

I agree about using other libraries for simple task. Also agree that the list should be empty. I use lazy empty list when the possibility it will be empty to guard against null ptrs and be able to operate on it if empty without making null checks.
@Mr00Anderson it’s worth noting that since Java 8, ArrayList instances created with the default constructor (new ArrayList<>()) do not create their backing array until the first element is added. So they are already lazily initialized and implementing another lazy initialization rarely pays off.
@Holger Thanks. I may have forgot that part. I tend to read documentation before performing such things; I did read before commenting, didn't catch the already lazy. I recently left Java to C++ too. Due to a few reasons with the future of Java and current state past Java 10 and my need for performance for my Multiplayer game.
This still contains the bug from the original code. At first the list is empty, so you set it to a singletonList. The next time you call this code, it's not empty, so you add another book to it. Then it throws an UnsupportedOperationException because you can't add anything to a singletonList.
@KlitosKyriacou Because you have used Collections.singletonList which is immutable, you will not be able to... this entire question now that I have read it again - is very misleading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.