Using streams for a null-safe conversion from an array to listConverting Array to ListCreate ArrayList from arrayHow to simplify a null-safe compareTo() implementation?Converting array to list in JavaConvert list to array in JavaRetrieving a List from a java.util.stream.Stream in Java 8How to Convert a Java 8 Stream to an Array?Java 8 Stream and operation on arraysHow can I create a stream from an array?How to sum a list of integers with java streams?Java 8 stream - how to properly make NPE-safe stream

Is there a reason to prefer HFS+ over APFS for disk images in High Sierra and/or Mojave?

Should I warn new/prospective PhD Student that supervisor is terrible?

When and why was runway 07/25 at Kai Tak removed?

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Why do Radio Buttons not fill the entire outer circle?

Grepping string, but include all non-blank lines following each grep match

Difference between shutdown options

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

Limit max CPU usage SQL SERVER with WSRM

Can you identify this lizard-like creature I observed in the UK?

Can I cause damage to electrical appliances by unplugging them when they are turned on?

What is this high flying aircraft over Pennsylvania?

Typing CO_2 easily

What should be the ideal length of sentences in a blog post for ease of reading?

Echo with obfuscation

How to leave product feedback on macOS?

Giving feedback to someone without sounding prejudiced

Isometric embedding of a genus g surface

Showing mass murder in a kid's book

Do people actually use the word "kaputt" in conversation?

How do I Interface a PS/2 Keyboard without Modern Techniques?

How do I prevent inappropriate ads from appearing in my game?

What the heck is gets(stdin) on site coderbyte?



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


Converting Array to ListCreate ArrayList from arrayHow to simplify a null-safe compareTo() implementation?Converting array to list in JavaConvert list to array in JavaRetrieving a List from a java.util.stream.Stream in Java 8How to Convert a Java 8 Stream to an Array?Java 8 Stream and operation on arraysHow can I create a stream from an array?How to sum a list of integers with java streams?Java 8 stream - how to properly make NPE-safe stream













8















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.










share|improve this question



















  • 3





    Your original code seems succinct enough

    – GBlodgett
    4 hours ago











  • Fair enough, but I'm curious as to the best way it can be done using streams.

    – risingTide
    4 hours ago






  • 1





    .map(Arrays::asList)

    – shmosel
    4 hours ago















8















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.










share|improve this question



















  • 3





    Your original code seems succinct enough

    – GBlodgett
    4 hours ago











  • Fair enough, but I'm curious as to the best way it can be done using streams.

    – risingTide
    4 hours ago






  • 1





    .map(Arrays::asList)

    – shmosel
    4 hours ago













8












8








8


1






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.










share|improve this question
















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.







java java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago







risingTide

















asked 4 hours ago









risingTiderisingTide

60841238




60841238







  • 3





    Your original code seems succinct enough

    – GBlodgett
    4 hours ago











  • Fair enough, but I'm curious as to the best way it can be done using streams.

    – risingTide
    4 hours ago






  • 1





    .map(Arrays::asList)

    – shmosel
    4 hours ago












  • 3





    Your original code seems succinct enough

    – GBlodgett
    4 hours ago











  • Fair enough, but I'm curious as to the best way it can be done using streams.

    – risingTide
    4 hours ago






  • 1





    .map(Arrays::asList)

    – shmosel
    4 hours ago







3




3





Your original code seems succinct enough

– GBlodgett
4 hours ago





Your original code seems succinct enough

– GBlodgett
4 hours ago













Fair enough, but I'm curious as to the best way it can be done using streams.

– risingTide
4 hours ago





Fair enough, but I'm curious as to the best way it can be done using streams.

– risingTide
4 hours ago




1




1





.map(Arrays::asList)

– shmosel
4 hours ago





.map(Arrays::asList)

– shmosel
4 hours ago












2 Answers
2






active

oldest

votes


















6














You might use the map :



List<String> ccAddrs = Optional.ofNullable(ccAddress)
.map(Arrays::asList)
.orElse(Collections.emptyList())





share|improve this answer


















  • 2





    @downvoter: Should let me know the reason :)

    – Mạnh Quyết Nguyễn
    4 hours ago











  • They don't . Because they are random clickers

    – soorapadman
    2 hours ago


















4














In my opinion, the code that you have so far is perfectly readable. I think using a Stream for something like this will just complicate things. If you still want to use a Stream, then something like the following would work:



mailObject.setCcAddresses(Stream.ofNullable(ccAddresses)
.flatMap(Arrays::stream)
.collect(Collectors.toUnmodifiableList()));


As you can see, this is a more unreadable, and I wouldn't recommend it over your simple ternary expression.




Your Optional solution is slightly more readable and would look like the following:



mailObject.setCcAddresses(Optional.ofNullable(ccAddresses)
.map(Arrays::asList)
.orElse(Collections.emptyList()));





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55272522%2fusing-streams-for-a-null-safe-conversion-from-an-array-to-list%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    You might use the map :



    List<String> ccAddrs = Optional.ofNullable(ccAddress)
    .map(Arrays::asList)
    .orElse(Collections.emptyList())





    share|improve this answer


















    • 2





      @downvoter: Should let me know the reason :)

      – Mạnh Quyết Nguyễn
      4 hours ago











    • They don't . Because they are random clickers

      – soorapadman
      2 hours ago















    6














    You might use the map :



    List<String> ccAddrs = Optional.ofNullable(ccAddress)
    .map(Arrays::asList)
    .orElse(Collections.emptyList())





    share|improve this answer


















    • 2





      @downvoter: Should let me know the reason :)

      – Mạnh Quyết Nguyễn
      4 hours ago











    • They don't . Because they are random clickers

      – soorapadman
      2 hours ago













    6












    6








    6







    You might use the map :



    List<String> ccAddrs = Optional.ofNullable(ccAddress)
    .map(Arrays::asList)
    .orElse(Collections.emptyList())





    share|improve this answer













    You might use the map :



    List<String> ccAddrs = Optional.ofNullable(ccAddress)
    .map(Arrays::asList)
    .orElse(Collections.emptyList())






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 4 hours ago









    Mạnh Quyết NguyễnMạnh Quyết Nguyễn

    11k1930




    11k1930







    • 2





      @downvoter: Should let me know the reason :)

      – Mạnh Quyết Nguyễn
      4 hours ago











    • They don't . Because they are random clickers

      – soorapadman
      2 hours ago












    • 2





      @downvoter: Should let me know the reason :)

      – Mạnh Quyết Nguyễn
      4 hours ago











    • They don't . Because they are random clickers

      – soorapadman
      2 hours ago







    2




    2





    @downvoter: Should let me know the reason :)

    – Mạnh Quyết Nguyễn
    4 hours ago





    @downvoter: Should let me know the reason :)

    – Mạnh Quyết Nguyễn
    4 hours ago













    They don't . Because they are random clickers

    – soorapadman
    2 hours ago





    They don't . Because they are random clickers

    – soorapadman
    2 hours ago













    4














    In my opinion, the code that you have so far is perfectly readable. I think using a Stream for something like this will just complicate things. If you still want to use a Stream, then something like the following would work:



    mailObject.setCcAddresses(Stream.ofNullable(ccAddresses)
    .flatMap(Arrays::stream)
    .collect(Collectors.toUnmodifiableList()));


    As you can see, this is a more unreadable, and I wouldn't recommend it over your simple ternary expression.




    Your Optional solution is slightly more readable and would look like the following:



    mailObject.setCcAddresses(Optional.ofNullable(ccAddresses)
    .map(Arrays::asList)
    .orElse(Collections.emptyList()));





    share|improve this answer





























      4














      In my opinion, the code that you have so far is perfectly readable. I think using a Stream for something like this will just complicate things. If you still want to use a Stream, then something like the following would work:



      mailObject.setCcAddresses(Stream.ofNullable(ccAddresses)
      .flatMap(Arrays::stream)
      .collect(Collectors.toUnmodifiableList()));


      As you can see, this is a more unreadable, and I wouldn't recommend it over your simple ternary expression.




      Your Optional solution is slightly more readable and would look like the following:



      mailObject.setCcAddresses(Optional.ofNullable(ccAddresses)
      .map(Arrays::asList)
      .orElse(Collections.emptyList()));





      share|improve this answer



























        4












        4








        4







        In my opinion, the code that you have so far is perfectly readable. I think using a Stream for something like this will just complicate things. If you still want to use a Stream, then something like the following would work:



        mailObject.setCcAddresses(Stream.ofNullable(ccAddresses)
        .flatMap(Arrays::stream)
        .collect(Collectors.toUnmodifiableList()));


        As you can see, this is a more unreadable, and I wouldn't recommend it over your simple ternary expression.




        Your Optional solution is slightly more readable and would look like the following:



        mailObject.setCcAddresses(Optional.ofNullable(ccAddresses)
        .map(Arrays::asList)
        .orElse(Collections.emptyList()));





        share|improve this answer















        In my opinion, the code that you have so far is perfectly readable. I think using a Stream for something like this will just complicate things. If you still want to use a Stream, then something like the following would work:



        mailObject.setCcAddresses(Stream.ofNullable(ccAddresses)
        .flatMap(Arrays::stream)
        .collect(Collectors.toUnmodifiableList()));


        As you can see, this is a more unreadable, and I wouldn't recommend it over your simple ternary expression.




        Your Optional solution is slightly more readable and would look like the following:



        mailObject.setCcAddresses(Optional.ofNullable(ccAddresses)
        .map(Arrays::asList)
        .orElse(Collections.emptyList()));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 4 hours ago

























        answered 4 hours ago









        Jacob G.Jacob G.

        16.3k52363




        16.3k52363



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55272522%2fusing-streams-for-a-null-safe-conversion-from-an-array-to-list%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar