How to handle nullable lists using java 8?












8














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.

























    8














    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.























      8












      8








      8


      2





      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 3 hours ago









      Aomine

      38.8k73365




      38.8k73365






      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 4 hours ago









      Kyle Bak

      412




      412




      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.
























          5 Answers
          5






          active

          oldest

          votes


















          6














          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





























            6















            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































              5















              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































                2














                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





























                  0














                  Have you tried much simpler approaches like using try catch for null pointer exception






                  share|improve this answer








                  New contributor




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














                  • 2




                    An NPE is an unchecked exception, meaning you shouldn't catch it
                    – GBlodgett
                    2 hours ago






                  • 1




                    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                    – Rob
                    1 hour ago











                  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









                  6














                  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


























                    6














                    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
























                      6












                      6








                      6






                      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 3 hours ago









                      Radiodef

                      31.6k126595




                      31.6k126595

























                          6















                          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




























                            6















                            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


























                              6












                              6








                              6







                              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 hours ago

























                              answered 2 hours ago









                              nullpointer

                              41.1k1086172




                              41.1k1086172























                                  5















                                  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




























                                    5















                                    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


























                                      5












                                      5








                                      5







                                      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 3 hours ago

























                                      answered 4 hours ago









                                      Aomine

                                      38.8k73365




                                      38.8k73365























                                          2














                                          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


























                                            2














                                            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
























                                              2












                                              2








                                              2






                                              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 1 hour ago









                                              Federico Peralta Schaffner

                                              21.8k43369




                                              21.8k43369























                                                  0














                                                  Have you tried much simpler approaches like using try catch for null pointer exception






                                                  share|improve this answer








                                                  New contributor




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














                                                  • 2




                                                    An NPE is an unchecked exception, meaning you shouldn't catch it
                                                    – GBlodgett
                                                    2 hours ago






                                                  • 1




                                                    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                    – Rob
                                                    1 hour ago
















                                                  0














                                                  Have you tried much simpler approaches like using try catch for null pointer exception






                                                  share|improve this answer








                                                  New contributor




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














                                                  • 2




                                                    An NPE is an unchecked exception, meaning you shouldn't catch it
                                                    – GBlodgett
                                                    2 hours ago






                                                  • 1




                                                    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                    – Rob
                                                    1 hour ago














                                                  0












                                                  0








                                                  0






                                                  Have you tried much simpler approaches like using try catch for null pointer exception






                                                  share|improve this answer








                                                  New contributor




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









                                                  Have you tried much simpler approaches like using try catch for null pointer exception







                                                  share|improve this answer








                                                  New contributor




                                                  I Aravinda 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 answer



                                                  share|improve this answer






                                                  New contributor




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









                                                  answered 2 hours ago









                                                  I Aravinda

                                                  215




                                                  215




                                                  New contributor




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





                                                  New contributor





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






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








                                                  • 2




                                                    An NPE is an unchecked exception, meaning you shouldn't catch it
                                                    – GBlodgett
                                                    2 hours ago






                                                  • 1




                                                    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                    – Rob
                                                    1 hour ago














                                                  • 2




                                                    An NPE is an unchecked exception, meaning you shouldn't catch it
                                                    – GBlodgett
                                                    2 hours ago






                                                  • 1




                                                    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                    – Rob
                                                    1 hour ago








                                                  2




                                                  2




                                                  An NPE is an unchecked exception, meaning you shouldn't catch it
                                                  – GBlodgett
                                                  2 hours ago




                                                  An NPE is an unchecked exception, meaning you shouldn't catch it
                                                  – GBlodgett
                                                  2 hours ago




                                                  1




                                                  1




                                                  This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                  – Rob
                                                  1 hour ago




                                                  This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
                                                  – Rob
                                                  1 hour ago










                                                  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

                                                  Morgemoulin

                                                  Scott Moir

                                                  Souastre