How to handle nullable lists using java 8?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












13














I'm making a service call and trying to handle response.
Response might have a list of something. That list might be null.



Moreover, if list not null or not empty, then
it needs to be filtered.
In the code "entry" reference might be null if filtering gives nothing or response list is empty or null.



Currently i'm getting NPE when i try to use stream() on a null response list.
How can i handle this situation?



@Getter
public class ServiceResponse
List<ResponseEntry> entryList;


@Getter
public class ResponseEntry
String value;



ServiceResponse serviceResponse = service.getServiceResponse();
ResponseEntry entry = serviceResponse.getEntryList()
.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst()
.orElse(null);

if (entry == null) ...











share|improve this question



















  • 3




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    Dec 27 '18 at 6:41















13














I'm making a service call and trying to handle response.
Response might have a list of something. That list might be null.



Moreover, if list not null or not empty, then
it needs to be filtered.
In the code "entry" reference might be null if filtering gives nothing or response list is empty or null.



Currently i'm getting NPE when i try to use stream() on a null response list.
How can i handle this situation?



@Getter
public class ServiceResponse
List<ResponseEntry> entryList;


@Getter
public class ResponseEntry
String value;



ServiceResponse serviceResponse = service.getServiceResponse();
ResponseEntry entry = serviceResponse.getEntryList()
.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst()
.orElse(null);

if (entry == null) ...











share|improve this question



















  • 3




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    Dec 27 '18 at 6:41













13












13








13


4





I'm making a service call and trying to handle response.
Response might have a list of something. That list might be null.



Moreover, if list not null or not empty, then
it needs to be filtered.
In the code "entry" reference might be null if filtering gives nothing or response list is empty or null.



Currently i'm getting NPE when i try to use stream() on a null response list.
How can i handle this situation?



@Getter
public class ServiceResponse
List<ResponseEntry> entryList;


@Getter
public class ResponseEntry
String value;



ServiceResponse serviceResponse = service.getServiceResponse();
ResponseEntry entry = serviceResponse.getEntryList()
.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst()
.orElse(null);

if (entry == null) ...











share|improve this question















I'm making a service call and trying to handle response.
Response might have a list of something. That list might be null.



Moreover, if list not null or not empty, then
it needs to be filtered.
In the code "entry" reference might be null if filtering gives nothing or response list is empty or null.



Currently i'm getting NPE when i try to use stream() on a null response list.
How can i handle this situation?



@Getter
public class ServiceResponse
List<ResponseEntry> entryList;


@Getter
public class ResponseEntry
String value;



ServiceResponse serviceResponse = service.getServiceResponse();
ResponseEntry entry = serviceResponse.getEntryList()
.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst()
.orElse(null);

if (entry == null) ...








java java-8 java-stream optional






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 26 '18 at 23:22









Aomine

41.3k74071




41.3k74071










asked Dec 26 '18 at 23:09









Kyle BakKyle Bak

734




734







  • 3




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    Dec 27 '18 at 6:41












  • 3




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    Dec 27 '18 at 6:41







3




3




Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
– chrylis
Dec 27 '18 at 6:41




Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
– chrylis
Dec 27 '18 at 6:41












5 Answers
5






active

oldest

votes


















12















if list not null or not empty, then it needs to be filtered.




No need for Optional here, as it's not intended to replace simple if checks.



ResponseEntry entry = null;
List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
if(responseEntries != null && !responseEntries.isEmpty())
entry = responseEntries.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst()
.orElse(null);



  • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

On the other hand, the optional approach:



ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
.orElseGet(() -> Collections.emptyList())
.stream()
.filter(e -> "expectedValue".equals(e.getValue()))
.findFirst();

if(!entry.isPresent()) ... // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block


  • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.





share|improve this answer






























    8















    Stream.ofNullable (Java-9)




    Returns a sequential Stream containing a single element, if non-null,
    otherwise returns an empty Stream.




    Current Code



    ResponseEntry entry = serviceResponse.getEntryList() // List<ResponseEntry>
    .stream() // NPE here // Stream<ResponseEntry>
    .filter(e -> "expectedValue".equals(e.getValue())) // filter
    .findFirst() // Optional<ResponseEntry>
    .orElse(null); // or else null


    Updated Code



    ResponseEntry entry = Stream.ofNullable(serviceResponse.getEntryList()) // Stream<List<ResponseEntry>>
    .flatMap(List::stream) // Stream<ResponseEntry>
    .filter(e -> "expectedValue".equals(e.getValue())) // filter here
    .findFirst() // Optional<ResponseEntry>
    .orElse(null); // or else null




    Optional.stream (Java-9)




    returns a sequential Stream containing only that value, otherwise
    returns an empty Stream.




    ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
    .stream() // Stream<List<ResponseEntry>>
    .flatMap(List::stream) // Stream<ResponseEntry>
    .filter(e -> "expectedValue".equals(e.getValue())) // filter here
    .findFirst() // Optional<ResponseEntry>
    .orElse(null); // or else null




    Optional.isEmpty(Java-11)




    If a value is not present, returns true, otherwise false




    Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()) // Optional<List<ResponseEntry>>
    .orElseGet(Collections::emptyList) // or else empty List
    .stream() // Stream<ResponseEntry>
    .filter(e -> "expectedValue".equals(e.getValue())) // filter
    .findFirst(); // Optional<ResponseEntry>

    if (entry.isEmpty()) // !entry.isPresent in java-8
    // Do your work here






    share|improve this answer






























      7














      In Java 9, you could use the new method Objects.requireNonNullElse(T,T):



      Objects.requireNonNullElse(serviceResponse.getEntryList(),
      Collections.emptyList())


      Apache Commons Collections actually has a method ListUtils.emptyIfNull(List<T>) which returns an empty list if the argument list is null. That's even better, but Objects.requireNonNullElse is the closest thing to it in Java SE.



      If you're restricted to just Java 8, then I agree with Aomine's answer that trying to do something like go through Optional is worse than an if statement.






      share|improve this answer




























        5














        You could simply use the ternary operator:



        ServiceResponse serviceResponse = service.getServiceResponse();
        List<ResponseEntry> list = serviceResponse.getEntryList();

        ResponseEntry entry = (list == null ? Collections.emptyList() : list)
        .stream()
        .filter(e -> "expectedValue".equals(e.getValue()))
        .findFirst()
        .orElse(null);

        if (entry == null) ...


        Sometimes, traditional is better IMO.






        share|improve this answer




























          1














          Another option would be to use the Optional monad:



          Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()).flatMap(list ->
          list.stream().filter(e -> "expectedValue".equals(e.getValue())).findFirst()
          );

          if (!entry.isPresent())




          You might even use orElseGet instead of that if statement if your objective is to build (and return) a value, instead of executing a side effect.






          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%2f53938100%2fhow-to-handle-nullable-lists-using-java-8%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            12















            if list not null or not empty, then it needs to be filtered.




            No need for Optional here, as it's not intended to replace simple if checks.



            ResponseEntry entry = null;
            List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
            if(responseEntries != null && !responseEntries.isEmpty())
            entry = responseEntries.stream()
            .filter(e -> "expectedValue".equals(e.getValue()))
            .findFirst()
            .orElse(null);



            • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

            On the other hand, the optional approach:



            ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
            .orElseGet(() -> Collections.emptyList())
            .stream()
            .filter(e -> "expectedValue".equals(e.getValue()))
            .findFirst();

            if(!entry.isPresent()) ... // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block


            • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.





            share|improve this answer



























              12















              if list not null or not empty, then it needs to be filtered.




              No need for Optional here, as it's not intended to replace simple if checks.



              ResponseEntry entry = null;
              List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
              if(responseEntries != null && !responseEntries.isEmpty())
              entry = responseEntries.stream()
              .filter(e -> "expectedValue".equals(e.getValue()))
              .findFirst()
              .orElse(null);



              • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

              On the other hand, the optional approach:



              ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
              .orElseGet(() -> Collections.emptyList())
              .stream()
              .filter(e -> "expectedValue".equals(e.getValue()))
              .findFirst();

              if(!entry.isPresent()) ... // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block


              • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.





              share|improve this answer

























                12












                12








                12







                if list not null or not empty, then it needs to be filtered.




                No need for Optional here, as it's not intended to replace simple if checks.



                ResponseEntry entry = null;
                List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
                if(responseEntries != null && !responseEntries.isEmpty())
                entry = responseEntries.stream()
                .filter(e -> "expectedValue".equals(e.getValue()))
                .findFirst()
                .orElse(null);



                • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

                On the other hand, the optional approach:



                ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                .orElseGet(() -> Collections.emptyList())
                .stream()
                .filter(e -> "expectedValue".equals(e.getValue()))
                .findFirst();

                if(!entry.isPresent()) ... // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block


                • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.





                share|improve this answer















                if list not null or not empty, then it needs to be filtered.




                No need for Optional here, as it's not intended to replace simple if checks.



                ResponseEntry entry = null;
                List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
                if(responseEntries != null && !responseEntries.isEmpty())
                entry = responseEntries.stream()
                .filter(e -> "expectedValue".equals(e.getValue()))
                .findFirst()
                .orElse(null);



                • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

                On the other hand, the optional approach:



                ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                .orElseGet(() -> Collections.emptyList())
                .stream()
                .filter(e -> "expectedValue".equals(e.getValue()))
                .findFirst();

                if(!entry.isPresent()) ... // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block


                • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 26 '18 at 23:34

























                answered Dec 26 '18 at 23:11









                AomineAomine

                41.3k74071




                41.3k74071























                    8















                    Stream.ofNullable (Java-9)




                    Returns a sequential Stream containing a single element, if non-null,
                    otherwise returns an empty Stream.




                    Current Code



                    ResponseEntry entry = serviceResponse.getEntryList() // List<ResponseEntry>
                    .stream() // NPE here // Stream<ResponseEntry>
                    .filter(e -> "expectedValue".equals(e.getValue())) // filter
                    .findFirst() // Optional<ResponseEntry>
                    .orElse(null); // or else null


                    Updated Code



                    ResponseEntry entry = Stream.ofNullable(serviceResponse.getEntryList()) // Stream<List<ResponseEntry>>
                    .flatMap(List::stream) // Stream<ResponseEntry>
                    .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                    .findFirst() // Optional<ResponseEntry>
                    .orElse(null); // or else null




                    Optional.stream (Java-9)




                    returns a sequential Stream containing only that value, otherwise
                    returns an empty Stream.




                    ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                    .stream() // Stream<List<ResponseEntry>>
                    .flatMap(List::stream) // Stream<ResponseEntry>
                    .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                    .findFirst() // Optional<ResponseEntry>
                    .orElse(null); // or else null




                    Optional.isEmpty(Java-11)




                    If a value is not present, returns true, otherwise false




                    Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()) // Optional<List<ResponseEntry>>
                    .orElseGet(Collections::emptyList) // or else empty List
                    .stream() // Stream<ResponseEntry>
                    .filter(e -> "expectedValue".equals(e.getValue())) // filter
                    .findFirst(); // Optional<ResponseEntry>

                    if (entry.isEmpty()) // !entry.isPresent in java-8
                    // Do your work here






                    share|improve this answer



























                      8















                      Stream.ofNullable (Java-9)




                      Returns a sequential Stream containing a single element, if non-null,
                      otherwise returns an empty Stream.




                      Current Code



                      ResponseEntry entry = serviceResponse.getEntryList() // List<ResponseEntry>
                      .stream() // NPE here // Stream<ResponseEntry>
                      .filter(e -> "expectedValue".equals(e.getValue())) // filter
                      .findFirst() // Optional<ResponseEntry>
                      .orElse(null); // or else null


                      Updated Code



                      ResponseEntry entry = Stream.ofNullable(serviceResponse.getEntryList()) // Stream<List<ResponseEntry>>
                      .flatMap(List::stream) // Stream<ResponseEntry>
                      .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                      .findFirst() // Optional<ResponseEntry>
                      .orElse(null); // or else null




                      Optional.stream (Java-9)




                      returns a sequential Stream containing only that value, otherwise
                      returns an empty Stream.




                      ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                      .stream() // Stream<List<ResponseEntry>>
                      .flatMap(List::stream) // Stream<ResponseEntry>
                      .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                      .findFirst() // Optional<ResponseEntry>
                      .orElse(null); // or else null




                      Optional.isEmpty(Java-11)




                      If a value is not present, returns true, otherwise false




                      Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()) // Optional<List<ResponseEntry>>
                      .orElseGet(Collections::emptyList) // or else empty List
                      .stream() // Stream<ResponseEntry>
                      .filter(e -> "expectedValue".equals(e.getValue())) // filter
                      .findFirst(); // Optional<ResponseEntry>

                      if (entry.isEmpty()) // !entry.isPresent in java-8
                      // Do your work here






                      share|improve this answer

























                        8












                        8








                        8







                        Stream.ofNullable (Java-9)




                        Returns a sequential Stream containing a single element, if non-null,
                        otherwise returns an empty Stream.




                        Current Code



                        ResponseEntry entry = serviceResponse.getEntryList() // List<ResponseEntry>
                        .stream() // NPE here // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null


                        Updated Code



                        ResponseEntry entry = Stream.ofNullable(serviceResponse.getEntryList()) // Stream<List<ResponseEntry>>
                        .flatMap(List::stream) // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null




                        Optional.stream (Java-9)




                        returns a sequential Stream containing only that value, otherwise
                        returns an empty Stream.




                        ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                        .stream() // Stream<List<ResponseEntry>>
                        .flatMap(List::stream) // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null




                        Optional.isEmpty(Java-11)




                        If a value is not present, returns true, otherwise false




                        Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()) // Optional<List<ResponseEntry>>
                        .orElseGet(Collections::emptyList) // or else empty List
                        .stream() // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter
                        .findFirst(); // Optional<ResponseEntry>

                        if (entry.isEmpty()) // !entry.isPresent in java-8
                        // Do your work here






                        share|improve this answer















                        Stream.ofNullable (Java-9)




                        Returns a sequential Stream containing a single element, if non-null,
                        otherwise returns an empty Stream.




                        Current Code



                        ResponseEntry entry = serviceResponse.getEntryList() // List<ResponseEntry>
                        .stream() // NPE here // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null


                        Updated Code



                        ResponseEntry entry = Stream.ofNullable(serviceResponse.getEntryList()) // Stream<List<ResponseEntry>>
                        .flatMap(List::stream) // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null




                        Optional.stream (Java-9)




                        returns a sequential Stream containing only that value, otherwise
                        returns an empty Stream.




                        ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                        .stream() // Stream<List<ResponseEntry>>
                        .flatMap(List::stream) // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter here
                        .findFirst() // Optional<ResponseEntry>
                        .orElse(null); // or else null




                        Optional.isEmpty(Java-11)




                        If a value is not present, returns true, otherwise false




                        Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()) // Optional<List<ResponseEntry>>
                        .orElseGet(Collections::emptyList) // or else empty List
                        .stream() // Stream<ResponseEntry>
                        .filter(e -> "expectedValue".equals(e.getValue())) // filter
                        .findFirst(); // Optional<ResponseEntry>

                        if (entry.isEmpty()) // !entry.isPresent in java-8
                        // Do your work here







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 27 '18 at 1:09

























                        answered Dec 27 '18 at 0:40









                        nullpointernullpointer

                        44k1095182




                        44k1095182





















                            7














                            In Java 9, you could use the new method Objects.requireNonNullElse(T,T):



                            Objects.requireNonNullElse(serviceResponse.getEntryList(),
                            Collections.emptyList())


                            Apache Commons Collections actually has a method ListUtils.emptyIfNull(List<T>) which returns an empty list if the argument list is null. That's even better, but Objects.requireNonNullElse is the closest thing to it in Java SE.



                            If you're restricted to just Java 8, then I agree with Aomine's answer that trying to do something like go through Optional is worse than an if statement.






                            share|improve this answer

























                              7














                              In Java 9, you could use the new method Objects.requireNonNullElse(T,T):



                              Objects.requireNonNullElse(serviceResponse.getEntryList(),
                              Collections.emptyList())


                              Apache Commons Collections actually has a method ListUtils.emptyIfNull(List<T>) which returns an empty list if the argument list is null. That's even better, but Objects.requireNonNullElse is the closest thing to it in Java SE.



                              If you're restricted to just Java 8, then I agree with Aomine's answer that trying to do something like go through Optional is worse than an if statement.






                              share|improve this answer























                                7












                                7








                                7






                                In Java 9, you could use the new method Objects.requireNonNullElse(T,T):



                                Objects.requireNonNullElse(serviceResponse.getEntryList(),
                                Collections.emptyList())


                                Apache Commons Collections actually has a method ListUtils.emptyIfNull(List<T>) which returns an empty list if the argument list is null. That's even better, but Objects.requireNonNullElse is the closest thing to it in Java SE.



                                If you're restricted to just Java 8, then I agree with Aomine's answer that trying to do something like go through Optional is worse than an if statement.






                                share|improve this answer












                                In Java 9, you could use the new method Objects.requireNonNullElse(T,T):



                                Objects.requireNonNullElse(serviceResponse.getEntryList(),
                                Collections.emptyList())


                                Apache Commons Collections actually has a method ListUtils.emptyIfNull(List<T>) which returns an empty list if the argument list is null. That's even better, but Objects.requireNonNullElse is the closest thing to it in Java SE.



                                If you're restricted to just Java 8, then I agree with Aomine's answer that trying to do something like go through Optional is worse than an if statement.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Dec 26 '18 at 23:55









                                RadiodefRadiodef

                                31.8k126596




                                31.8k126596





















                                    5














                                    You could simply use the ternary operator:



                                    ServiceResponse serviceResponse = service.getServiceResponse();
                                    List<ResponseEntry> list = serviceResponse.getEntryList();

                                    ResponseEntry entry = (list == null ? Collections.emptyList() : list)
                                    .stream()
                                    .filter(e -> "expectedValue".equals(e.getValue()))
                                    .findFirst()
                                    .orElse(null);

                                    if (entry == null) ...


                                    Sometimes, traditional is better IMO.






                                    share|improve this answer

























                                      5














                                      You could simply use the ternary operator:



                                      ServiceResponse serviceResponse = service.getServiceResponse();
                                      List<ResponseEntry> list = serviceResponse.getEntryList();

                                      ResponseEntry entry = (list == null ? Collections.emptyList() : list)
                                      .stream()
                                      .filter(e -> "expectedValue".equals(e.getValue()))
                                      .findFirst()
                                      .orElse(null);

                                      if (entry == null) ...


                                      Sometimes, traditional is better IMO.






                                      share|improve this answer























                                        5












                                        5








                                        5






                                        You could simply use the ternary operator:



                                        ServiceResponse serviceResponse = service.getServiceResponse();
                                        List<ResponseEntry> list = serviceResponse.getEntryList();

                                        ResponseEntry entry = (list == null ? Collections.emptyList() : list)
                                        .stream()
                                        .filter(e -> "expectedValue".equals(e.getValue()))
                                        .findFirst()
                                        .orElse(null);

                                        if (entry == null) ...


                                        Sometimes, traditional is better IMO.






                                        share|improve this answer












                                        You could simply use the ternary operator:



                                        ServiceResponse serviceResponse = service.getServiceResponse();
                                        List<ResponseEntry> list = serviceResponse.getEntryList();

                                        ResponseEntry entry = (list == null ? Collections.emptyList() : list)
                                        .stream()
                                        .filter(e -> "expectedValue".equals(e.getValue()))
                                        .findFirst()
                                        .orElse(null);

                                        if (entry == null) ...


                                        Sometimes, traditional is better IMO.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Dec 27 '18 at 1:52









                                        Federico Peralta SchaffnerFederico Peralta Schaffner

                                        22.1k43370




                                        22.1k43370





















                                            1














                                            Another option would be to use the Optional monad:



                                            Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()).flatMap(list ->
                                            list.stream().filter(e -> "expectedValue".equals(e.getValue())).findFirst()
                                            );

                                            if (!entry.isPresent())




                                            You might even use orElseGet instead of that if statement if your objective is to build (and return) a value, instead of executing a side effect.






                                            share|improve this answer

























                                              1














                                              Another option would be to use the Optional monad:



                                              Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()).flatMap(list ->
                                              list.stream().filter(e -> "expectedValue".equals(e.getValue())).findFirst()
                                              );

                                              if (!entry.isPresent())




                                              You might even use orElseGet instead of that if statement if your objective is to build (and return) a value, instead of executing a side effect.






                                              share|improve this answer























                                                1












                                                1








                                                1






                                                Another option would be to use the Optional monad:



                                                Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()).flatMap(list ->
                                                list.stream().filter(e -> "expectedValue".equals(e.getValue())).findFirst()
                                                );

                                                if (!entry.isPresent())




                                                You might even use orElseGet instead of that if statement if your objective is to build (and return) a value, instead of executing a side effect.






                                                share|improve this answer












                                                Another option would be to use the Optional monad:



                                                Optional<ResponseEntry> entry = Optional.ofNullable(serviceResponse.getEntryList()).flatMap(list ->
                                                list.stream().filter(e -> "expectedValue".equals(e.getValue())).findFirst()
                                                );

                                                if (!entry.isPresent())




                                                You might even use orElseGet instead of that if statement if your objective is to build (and return) a value, instead of executing a side effect.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 27 '18 at 13:37









                                                BergiBergi

                                                365k58544868




                                                365k58544868



























                                                    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.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • 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%2f53938100%2fhow-to-handle-nullable-lists-using-java-8%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

                                                    Peggy Mitchell

                                                    Palaiologos

                                                    The Forum (Inglewood, California)