If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea
Here's a variation on using optional as @Stas suggested, but also using the isEmpty immutable collection as originally requested in the question:
public static List addElement(List list, String toAdd) {
List newList = Optional.ofNullable(list).orElse(Collections.emptyList());
newList.add(toAdd);
return newList;
}
This approach is also the closest thing I can find to the nice ability in Javascript to use an empty array if the collection is null.
For example:
// no need to indent everything inside a null check of myObjects
for (MyObj myObj : Optional.ofNullable(myObjects).orElse(Collections.emptyList())){
// do stuff with myObj
}