Java return an empty list

arraylistjavareturn

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:

} else {
    return List.of();
}

If you are stuck with some version of java before 9:

} else { 
    return Collections.emptyList();
}

Notes:

  1. These constructs are the most efficient, because they reuse an existing instance of an empty list, so each time you ask for an empty list, no new list gets created. However, object allocation in Java is very inexpensive, so this should not really be a concern.
  2. The list returned by either List.of() or Collections.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.
  3. In general, functions are meant to return immutable entities, so if you are invoking a function which returns a collection and then you intend to modify that collection, you are doing it wrong. If you really need a collection that you can modify, you should instead write your function so that it populates a mutable list that you pass to it as a parameter, so it is evident that you, as the owner of the mutable list, are free to further modify the list after the function returns.