how to filter elements that throw exception during stream map



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








3















I was following the article https://www.oreilly.com/ideas/handling-checked-exceptions-in-java-streams for extracting a method into a method, in order to handle exceptions, and noticed the examples given only look clean since they don't actually compile because they miss a return statement.

Essentially I'm looking to have a parse method similar to this "divide" in the article example 3, but mine parses the list and in some scenarios it will throw errors log them and continue, like this:



public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.filter(Objects::nonNull)
.collect(Collectors.toList());

public String parse(String s)
try
// returns something or throws exceptions
catch (Exception e )
log(e)

return null;



As you can see from this code I cheated the compilation error by returning a null at the end of the parse method that I then filter nulls on my validator before collecting, and it looks appalling. Is there a better way to skip the values in a clean easy way?










share|improve this question



















  • 1





    If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

    – Holger
    Nov 15 '18 at 15:38







  • 1





    Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

    – ETO
    Nov 15 '18 at 15:53












  • I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

    – user7673492
    Nov 15 '18 at 15:59







  • 1





    Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

    – Holger
    Nov 15 '18 at 16:06


















3















I was following the article https://www.oreilly.com/ideas/handling-checked-exceptions-in-java-streams for extracting a method into a method, in order to handle exceptions, and noticed the examples given only look clean since they don't actually compile because they miss a return statement.

Essentially I'm looking to have a parse method similar to this "divide" in the article example 3, but mine parses the list and in some scenarios it will throw errors log them and continue, like this:



public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.filter(Objects::nonNull)
.collect(Collectors.toList());

public String parse(String s)
try
// returns something or throws exceptions
catch (Exception e )
log(e)

return null;



As you can see from this code I cheated the compilation error by returning a null at the end of the parse method that I then filter nulls on my validator before collecting, and it looks appalling. Is there a better way to skip the values in a clean easy way?










share|improve this question



















  • 1





    If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

    – Holger
    Nov 15 '18 at 15:38







  • 1





    Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

    – ETO
    Nov 15 '18 at 15:53












  • I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

    – user7673492
    Nov 15 '18 at 15:59







  • 1





    Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

    – Holger
    Nov 15 '18 at 16:06














3












3








3








I was following the article https://www.oreilly.com/ideas/handling-checked-exceptions-in-java-streams for extracting a method into a method, in order to handle exceptions, and noticed the examples given only look clean since they don't actually compile because they miss a return statement.

Essentially I'm looking to have a parse method similar to this "divide" in the article example 3, but mine parses the list and in some scenarios it will throw errors log them and continue, like this:



public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.filter(Objects::nonNull)
.collect(Collectors.toList());

public String parse(String s)
try
// returns something or throws exceptions
catch (Exception e )
log(e)

return null;



As you can see from this code I cheated the compilation error by returning a null at the end of the parse method that I then filter nulls on my validator before collecting, and it looks appalling. Is there a better way to skip the values in a clean easy way?










share|improve this question
















I was following the article https://www.oreilly.com/ideas/handling-checked-exceptions-in-java-streams for extracting a method into a method, in order to handle exceptions, and noticed the examples given only look clean since they don't actually compile because they miss a return statement.

Essentially I'm looking to have a parse method similar to this "divide" in the article example 3, but mine parses the list and in some scenarios it will throw errors log them and continue, like this:



public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.filter(Objects::nonNull)
.collect(Collectors.toList());

public String parse(String s)
try
// returns something or throws exceptions
catch (Exception e )
log(e)

return null;



As you can see from this code I cheated the compilation error by returning a null at the end of the parse method that I then filter nulls on my validator before collecting, and it looks appalling. Is there a better way to skip the values in a clean easy way?







java collections java-8 exception-handling java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 8:40









ETO

2,7361629




2,7361629










asked Nov 15 '18 at 15:25









user7673492user7673492

745




745







  • 1





    If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

    – Holger
    Nov 15 '18 at 15:38







  • 1





    Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

    – ETO
    Nov 15 '18 at 15:53












  • I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

    – user7673492
    Nov 15 '18 at 15:59







  • 1





    Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

    – Holger
    Nov 15 '18 at 16:06













  • 1





    If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

    – Holger
    Nov 15 '18 at 15:38







  • 1





    Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

    – ETO
    Nov 15 '18 at 15:53












  • I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

    – user7673492
    Nov 15 '18 at 15:59







  • 1





    Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

    – Holger
    Nov 15 '18 at 16:06








1




1





If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

– Holger
Nov 15 '18 at 15:38






If parse never returns null in the successful case, that’s a good solution. An alternative would be to let parse return an Optional<String>, but before Java 9, the stream code would not look better than what you already have. Starting with Java 9, you could use .flatMap(s -> parse(s).stream()) then.

– Holger
Nov 15 '18 at 15:38





1




1





Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

– ETO
Nov 15 '18 at 15:53






Good point. But I would split your .flatMap(s -> parse(s).stream()) into two steps like .map(this::parse).flatMap(Optional::stream). IMHO this is easier to read.

– ETO
Nov 15 '18 at 15:53














I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

– user7673492
Nov 15 '18 at 15:59






I actually consider to use Optional but doing .filter(Optional::isPresent).map(Optional::get) is a lot more to read that just .filter(Objects::nonNull) but yes it may cause someone in the future to reuse my method and take a null pointer to the chin. By the way java 9 and 10 are not supported by oracle anymore, I assume that optional flatmap optimization would work with java 11, is that correct?

– user7673492
Nov 15 '18 at 15:59





1




1





Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

– Holger
Nov 15 '18 at 16:06






Of course, it will work in Java 11 too. For Java 8, you may create a helper method, public static <T> Stream<T> stream(Optional<T> o) return o.map(Stream::of).orElseGet(Stream::empty); . Then, you can use a solution close to the Java 9+ variant, .flatMap(s -> stream(parse(s))).

– Holger
Nov 15 '18 at 16:06













1 Answer
1






active

oldest

votes


















2














As for me your way of skipping null elements is pretty good.



However if you want to do it in functional way, then avoid returning null at all. Return an Optional instead:



public Optional<String> parse(String s)
try
return Optional.of(<parsed_value>);
catch (Exception e )
log(e);

return Optional.empty();



Java 1.8 solution:



public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());



Java 1.9+ solution: (as proposed by @Holger already):



 public List<String> validator(List<String> values) 
return values.stream()
.map(this::parse)
.flatMap(Optional::stream)
.collect(Collectors.toList());






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%2f53322674%2fhow-to-filter-elements-that-throw-exception-during-stream-map%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    As for me your way of skipping null elements is pretty good.



    However if you want to do it in functional way, then avoid returning null at all. Return an Optional instead:



    public Optional<String> parse(String s)
    try
    return Optional.of(<parsed_value>);
    catch (Exception e )
    log(e);

    return Optional.empty();



    Java 1.8 solution:



    public List<String> validator(List<String> values) 
    return values.stream()
    .map(this::parse)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(Collectors.toList());



    Java 1.9+ solution: (as proposed by @Holger already):



     public List<String> validator(List<String> values) 
    return values.stream()
    .map(this::parse)
    .flatMap(Optional::stream)
    .collect(Collectors.toList());






    share|improve this answer





























      2














      As for me your way of skipping null elements is pretty good.



      However if you want to do it in functional way, then avoid returning null at all. Return an Optional instead:



      public Optional<String> parse(String s)
      try
      return Optional.of(<parsed_value>);
      catch (Exception e )
      log(e);

      return Optional.empty();



      Java 1.8 solution:



      public List<String> validator(List<String> values) 
      return values.stream()
      .map(this::parse)
      .filter(Optional::isPresent)
      .map(Optional::get)
      .collect(Collectors.toList());



      Java 1.9+ solution: (as proposed by @Holger already):



       public List<String> validator(List<String> values) 
      return values.stream()
      .map(this::parse)
      .flatMap(Optional::stream)
      .collect(Collectors.toList());






      share|improve this answer



























        2












        2








        2







        As for me your way of skipping null elements is pretty good.



        However if you want to do it in functional way, then avoid returning null at all. Return an Optional instead:



        public Optional<String> parse(String s)
        try
        return Optional.of(<parsed_value>);
        catch (Exception e )
        log(e);

        return Optional.empty();



        Java 1.8 solution:



        public List<String> validator(List<String> values) 
        return values.stream()
        .map(this::parse)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());



        Java 1.9+ solution: (as proposed by @Holger already):



         public List<String> validator(List<String> values) 
        return values.stream()
        .map(this::parse)
        .flatMap(Optional::stream)
        .collect(Collectors.toList());






        share|improve this answer















        As for me your way of skipping null elements is pretty good.



        However if you want to do it in functional way, then avoid returning null at all. Return an Optional instead:



        public Optional<String> parse(String s)
        try
        return Optional.of(<parsed_value>);
        catch (Exception e )
        log(e);

        return Optional.empty();



        Java 1.8 solution:



        public List<String> validator(List<String> values) 
        return values.stream()
        .map(this::parse)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());



        Java 1.9+ solution: (as proposed by @Holger already):



         public List<String> validator(List<String> values) 
        return values.stream()
        .map(this::parse)
        .flatMap(Optional::stream)
        .collect(Collectors.toList());







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 16:01

























        answered Nov 15 '18 at 15:51









        ETOETO

        2,7361629




        2,7361629





























            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%2f53322674%2fhow-to-filter-elements-that-throw-exception-during-stream-map%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

            Kleinkühnau

            Makov (Slowakei)

            Deutsches Schauspielhaus