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";
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.
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.
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.
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)
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With