Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using streams for a null-safe conversion from an array to list

I'm looking for a succinct way to rewrite a piece of Java code so that it uses streams to convert an array to a list in a null-safe fashion. Here's the original code:

public MailObject toMailObject(final String[] ccAddresses) {
    final MailObject mailObject = new MailObject();

    // line of code to be altered
    mailObject.setCcAddresses(ccAddresses == null 
        ? Collections.emptyList() : Arrays.asList(ccAddresses));

    // other necessary code

    return mailObject;
}

I've thought of doing something like this:

// psuedocode that obviously doesn't compile
Optional.ofNullable(ccAddresses).SOMETHING.orElse(Collections.emptyList());

where SOMETHING would be along the lines of:

Arrays.stream(ints).collect(Collectors.toList());

but I can't seem to get the syntax quite right.

This question was helpful but didn't exactly address my issue. Could anyone point me in the right direction? I feel like I'm close...

Thank you very much for your time.

like image 342
risingTide Avatar asked Mar 21 '19 01:03

risingTide


People also ask

Can you cast an array to a List?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

Can we convert Stream to List in Java?

Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.


Video Answer


1 Answers

You might use the map :

List<String> ccAddrs = Optional.ofNullable(ccAddress)
                               .map(Arrays::asList)
                               .orElse(Collections.emptyList())
like image 193
Mạnh Quyết Nguyễn Avatar answered Sep 30 '22 18:09

Mạnh Quyết Nguyễn