No need to check list size before using stream
Javastreamcollection
Most of the time, the expected result is the same for an empty list and collecting an empty stream.
In this example, the expected result is an empty string.
Examples
Example 1:
Negative
Incorrect implementation that violates the practice.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Zoo {
private final List<Animal> animals = new ArrayList<>();
public void add(Animal animal) {
animals.add(animal);
}
public String animalsNames() {
if (animals.isEmpty()) {
return "";
}
return animals.stream()
.map(Animal::name)
.collect(Collectors.joining());
}
}