How can I replace any instances of null with an empty List in my stream?

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

Answers (1)

Ryuzaki L
Ryuzaki L

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

Related Questions