I have my Java method as below;
public List<Lookup> findAll(String lang) {
Query query = entityManager.createNamedQuery("Lookup.findAll");
if (isValidLang(lang)) {
query.setParameter("lang", lang);
return query.getResultList();
} else {
//return empty list
}
}
Now the method returns List for valid matches of lang.
But if that is not the case, I want to return an empty list. My question is how do I update the code & what is the best way to return an empty list so that the code does not fail ?
Best Answer
If you are using java 9 or later:
If you are stuck with some version of java before 9:
Notes:
List.of()
orCollections.emptyList()
is secretly immutable. By "secretly" I mean that it exposes mutation methods, but if you make the mistake of invoking any of those methods, you will be slapped with a runtime exception. In other, better languages than Java, (for example, in Scala,) there exist immutable / unmodifiable collections, but Java does not have such a thing "out of the box". So, if you are sticking with Java in 2020, you are accepting the possibility that not all of your collections can be written to, despite the fact that they all look as if they can be written to.