I have the following code which works on two values viz. a List
of String
and a String
. Both the List
and String
can be null
.
List<String> myStringList = getMyStringList(); // may return null
String myString = "abc"; // may be null
List<String> finalStringList = Optional.ofNullable(myStringList)
.map(strings -> strings.stream()
.filter(obj -> StringUtils.isEmpty(myString)
|| myString.equals(obj))
.collect(Collectors.toList()))
.orElseGet(ArrayList::new);
Idea is:
If myStringList
is null
, then result in an empty ArrayList
.
If myString
is null
, then return myStringList
as is.
If myString
is not null, then loop through the list and return all items matching myString
.
Problem is, with solution above, I still loop through the whole list (strings.stream
) even when myString
is null.
Assuming myStringList
is very big, how can I avoid looping the list for the case when myString
is null?
That is,
1) do a null check on the list. If null, return a new empty list.
2) do a null check on myString
. If null, return the list as is WITHOUT LOOPING.
3) if myString
is not null, loop through the list and return the filtered list.