Explain Codes LogoExplain Codes Logo

Null check in an enhanced for loop

java
null-checks
best-practices
java-8
Anton ShumikhinbyAnton Shumikhin·Mar 1, 2025
TLDR
for (YourType item : yourCollection) { if (item != null) { // Continue processing the sacred non-null item here } }

We perform a direct null check on the item during iteration. This vanquishes the NullPointerException and helps continue the loop fearlessly. But wait, we haven't ensured yourCollection isn't null yet, have we? Let's do just that before the loop for safe and smooth sailing.

Suit up before the battle: Pre-loop null checks

A surefire way to ensure your code doesn't bump its head at runtime is to perform a null check before entering the loop.

if (yourCollection == null) { // "Hold up! This collection can't be null!" Throw an IllegalArgumentException throw new IllegalArgumentException("Collection is null, and it was supposed to be wearing armor!"); } // Rest easy, now loop without fearing NullPointerException for (YourType item : yourCollection) { // Unleash processing power }

Or embrace Optional to keep things looking clean and dandy:

yourCollection = Optional.ofNullable(yourCollection).orElse(Collections.emptyList()); // Time to loop and swoop, with no fear of null creeping in for (YourType item : yourCollection) { // Commence operation process-each-item }

Enter the utility method: Handling null checks like a pro

Why repeat when you can reuse? Let's create a utility method to handle the uncool null checks in our supercool loop:

public static <T> Iterable<T> safetyFirst(Iterable<T> iterable) { // If iterable is null, gives a safe emptyIterator. Else, returns iterable as is. return iterable == null ? Collections::emptyIterator : iterable; } // Implement the utility method to enjoy "Null worries, mate" looping for (YourType item : safetyFirst(yourCollection)) { // Commence operation process-each-item }

If third-party libraries are your thing, you can use the ready-made ListUtils.emptyIfNull from Apache Commons Collections:

for (YourType item : ListUtils.emptyIfNull(yourCollection)) { // Let the processing party commence }

Quick escape plan: Abort on null for reduced complexity

Get an early ticket out of the fuss with identifying null. If a null signifies an unexpected scenario, escape early!

if (yourCollection == null) { // This is the time to make a swift quarantine exit, log error or handle it your own style return; } // With nulls taken care of, loop freely and easily for (YourType item : yourCollection) { // Command: Process-var-item is a go }

As a bonus tip, always return empty collections instead of null from your methods.

Staying contemporary: Modern Java practices

Newer versions of Java, especially Java 8 and onwards, have bestowed us with fantastic ways to handle nullable values.

yourCollection.stream() .filter(Objects::nonNull) .forEach(item -> { // Process each non-null item, null ones got filtered out already. Thanks Java 8! });

Keep it clean and efficient with readability and null check in loops

Keep the code as clean as a freshly scrubbed potato with precise and easy-to-understand null checks within loops.

Arrays.stream(yourArray) .filter(Objects::nonNull) .forEach(item -> { // 'null' who? Never heard of it. Process each item, null-free. });

Did you know? You can sterilize potential null arrays into harmless empty ones and effectively streamline iterations, using ArrayUtils.nullToEmpty from Apache Commons Lang!

Clarity in pattern: Consistent null handling

Create a consistent pattern for handling nulls in your code for enhanced readability and easy debugging. Adhere to performant practices or cook up your tailored strategy - the ball's in your court!