Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for non empty list inside a list using Java 8 features

I have a code fragment that I want to make more concise yet readable using Java 8 features like lambdas/streams etc.

Basically, there is a list of items and each item has a list of errors. If there is at least one item with at least one error, "failure" needs to be returned. If no items with any error, return "success".

Optional<List<Item>> optionalItemList = Optional.ofNullable(message.getItems());

if (optionalItemList.isPresent())
    for (Item item : optionalItemList.get()) {
        Optional<List<Error>> optionalErrorList = Optional.ofNullable((item.getErrors()));
        if(optionalErrorList.isPresent())
            if (!optionalErrorList.get().isEmpty()) {
                return "failure";
            }
        }
        return "success";
like image 769
user10937286 Avatar asked Jan 19 '19 11:01

user10937286


People also ask

Is an empty list a null list?

An empty collection isn't the same as null . An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.

What is the use of optional class in Java 8?

Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.

How do you check a list is empty or not in Java 8?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

What is optional ofNullable in Java?

The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned. public static <T> Optional<T> ofNullable(T value)


1 Answers

Optional is not meant to replace if statements, but to be used as a return value of methods. So I think you'd better not use it for this task. You can use the ternary operator along with Stream.allMatch instead:

return message.getItems() == null || 
       message.getItems().stream()
              .allMatch(i -> i.getErrors() == null || i.getErrors().isEmpty()) ?
      "success" :
      "failure";

On a side note, methods should never return null collections. The absence of elements should be expressed by returning empty collections. This would have made your code a lot easier:

return message.getItems().stream().allMatch(i -> i.getErrors().isEmpty()) ?
      "success" :
      "failure";
like image 140
fps Avatar answered Sep 19 '22 07:09

fps