How to handle nullable lists using java 8?












12














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









New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    2 days ago
















12














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









New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    2 days ago














12












12








12


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









New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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









New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 2 days ago









Aomine

39.3k73669




39.3k73669






New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









Kyle Bak

664




664




New contributor




Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Kyle Bak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    2 days ago














  • 2




    Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
    – chrylis
    2 days ago








2




2




Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
– chrylis
2 days ago




Why might the list be null? The preferred return for list-valued methods with no reply is emptyList().
– chrylis
2 days ago












5 Answers
5






active

oldest

votes


















11















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
            });


            }
            });






            Kyle Bak is a new contributor. Be nice, and check out our Code of Conduct.










            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









            11















            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




























              11















              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


























                11












                11








                11







                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 2 days ago

























                answered 2 days ago









                Aomine

                39.3k73669




                39.3k73669

























                    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 2 days ago

























                        answered 2 days ago









                        nullpointer

                        41.6k1088175




                        41.6k1088175























                            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 2 days ago









                                Radiodef

                                31.7k126596




                                31.7k126596























                                    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 2 days ago









                                        Federico Peralta Schaffner

                                        21.9k43370




                                        21.9k43370























                                            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 yesterday









                                                Bergi

                                                363k58540866




                                                363k58540866






















                                                    Kyle Bak is a new contributor. Be nice, and check out our Code of Conduct.










                                                    draft saved

                                                    draft discarded


















                                                    Kyle Bak is a new contributor. Be nice, and check out our Code of Conduct.













                                                    Kyle Bak is a new contributor. Be nice, and check out our Code of Conduct.












                                                    Kyle Bak is a new contributor. Be nice, and check out our Code of Conduct.
















                                                    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

                                                    Human spaceflight

                                                    Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

                                                    張江高科駅