Skip to content
Advertisement

More succinct code for a defensive copy using Guava’s immutable types?

I want to make a defensive copy of a collection passed into a method using Guava’s immutable types, e.g. an ImmutableList. I must also be able to deal with null input and treat that like an empty collection.

The cleanest I could come up with was this:

JavaScript

Is there something more readable, preferably without the ternary operator? I wouldn’t consider Optional.of(strings).map(...).orElse(...) as a nice alternative due to the reasoning that I share with this answer.

Advertisement

Answer

You can use MoreObjects.firstNonNull, which is also from Guava:

JavaScript

Alternatively ListUtils.emptyIfNull is a similar but more specialized method in Apache Commons Collections which is more clear and easier to read in my opinion:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement