It's very seldom necessary to do (pseudocode):
if(input list is empty) {
return an empty list
} else {
map each entry in input list to output list
}
... because every mainstream way of mapping an input list to an output list produces an empty list "automatically" for an empty input. For example:
List<String> input = Collections.emptyList();
List<String> output = new ArrayList<>();
for(String entry : input) {
output.add(entry.toLowerCase());
}
return output;
... will return an empty list. To treat an empty list as a special case makes for wasted code, and less expressive code.
Likewise, the modern Java approach of using Streams does the same:
List<String> output = input.stream()
.map( s -> s.toLowerCase())
.collect(Collectors.toList());
... will create an empty List in output, with no "special" handling for an empty input.
Collections.emptyList() returns a class that specifically implements an immutable, empty list. It has a very simple implementation, for example its size() is just return 0;.
But this means your caller won't be able to modify the returned list -- only if it's empty. Although immutability is a good thing, it's inconsistent to sometimes return a immutable list and other times not, and this could result in errors you detect late. If you want to enforce immutability, to it always by wrapping the response in Collections.unmodifiableList(), or using an immutable list from a library like Guava.
You also test whether the input is null. Consider whether this is necessary. Who's going to be calling the method? If it's just you, then don't do that! If you know you're not going to do it, your code needn't check for it.
If it's a public API for other programmers, you might need to handle nulls gratefully, but in many cases it's entirely appropriate to document that the input mustn't be null, and just let it throw a NullPointerException if it happens (or you can force one early by starting your method with Objects.requireNonNull(input).
Conclusion: my recommendation is:
List<String> doSomething(String input){
Objects.requireNonNull(input); // or omit this and let an
// exception happen further down
return doMoreProcessingOn(getListfromSomewhereElse(input));
}
It's best if doMoreProcessingOn() produces a new List, rather than modifying input.
return getListfromSomewhereElse(input)whether it is empty or not?if (input != null) return getListFromSomewhereElse(input); return Collections.emptyList();