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 ?
emptyList() returns an immutable list, i.e., a list to which you cannot add elements if you want to perform any operation on your list, then create new instance of list and return it. if (isValidLang(lang)) { query. setParameter("lang", lang); return query.
The emptyList() method returns an empty immutable list.
Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns.
Return an Empty Array Using new int[0] in Java To return an empty array from a function, we can create a new array with a zero size. In the example below, we create a function returnEmptyArray() that returns an array of int . We return new int[0] that is an empty array of int .
This should do it:
} else { return Collections.emptyList(); }
Notes:
Collections.emptyList()
there is also List.of()
.Collections.emptyList()
and List.of()
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 get an 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.Collections.emptyList()
returns an immutable list, i.e., a list to which you cannot add elements if you want to perform any operation on your list, then create new instance of list and return it.
if (isValidLang(lang)) { query.setParameter("lang", lang); return query.getResultList(); } else { return new ArrayList<Lookup>(); // return array list instance. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With