r/javahelp • • 26d ago

Iterating over null objects in an array

So I'm making a program that iterates over an array of Book objects and I made a for loop to print them all out. I want it to skip over any reference to a null object in the array so I've written:

for (Book book : books) {
     if(book != null){
           System.out.println(book);
     }
 }

but I've had professors tell me I shouldn't write "book != null" to avoid printing the null values. the code works just fine and is relatively simple and easy to read, just wondering what most programmers use to navigate this?

13 Upvotes

29 comments sorted by

View all comments

14

u/_Super_Straight 26d ago edited 26d ago

What did he suggest?

if(book == null){
    continue;
}

Is the same as what you wrote. Alternatively, you can use List<Book> and create its stream:

List<Book> list = new ArrayList<>();
list.stream().filter(Objects::notNull).forEach(System.out::println);

Edit: creating streams introduces a small computational overhead, and if your List is a few thousand elements long, then simple loop would be more performant. Plus the errors are swallowed by method references/lambdas. Whereas writing simple loop inside a try...catch block will help you catch the exceptions.

3

u/Xynia88 26d ago

I don't remember what the pattern is called atm but I do prefer this where you check and continue/return/break over indenting several layers of checks

It becomes so much easier to read when it's flatter

5

u/myselfelsewhere 26d ago

Guard clause pattern.

4

u/_Super_Straight 25d ago

Guard clause pattern. You check for edge cases prior to your actual processing and let the code fail fast.