I am trying to write code to filter elements from a list if they exist in the another list.
The business logic requires me to return all elements from the first list if the second list is empty.
List<String> list1 = Arrays.asList("a","b","c","d");
//List<String> list2 = Arrays.asList("a","d");
List<String> list2 = Collections.emptyList();
if (!list2.isEmpty()) {
List<String> finalList = list1.stream()
.map(x -> x)
.filter(x -> list2.isEmpty() && list2.contains(x))
.collect(toList());
return finalList;
} else {
return list1;
}
Is there a better way to do it? Preferably, in a single lambda function.