Reputation: 264
In my method below, the variable n
can be null, and if it is null I want to return an empty list eg something like List.of
. How can I amend the below method to ensure that if a null is found, an empty List
is returned and not removed? I tried using filter
which I've commented out below, but that just removes any instances where null is found.
private List<Account> getNames(MetaData metadata){
return metadata.getNames()
.stream()
.map(n -> createAccount(n, metadata.getType()))
//.filter(n -> n.getFinalName() != null)
.collect(Collectors.toList());
}
private Account createAccount(String n, Metadata metadata){...}
Upvotes: 0
Views: 1117
Reputation: 40048
You can use ternary operator
return metadata.getNames()
.stream()
.map(n -> n!=null ? createAccount(n, metadata.getType()) : /* else do something */)
.collect(Collectors.toList());
Upvotes: 2