Issue
How do I do sorting with an Optional? The following is not working. mainProducts
or productSublist
maybe null. We are returning productSubList
sorted by Date .
List<ProductSubList> productSubList = Optional.of(mainProducts)
.map(MainProducts::getProductSubList)
.ifPresent(list -> list.stream().sorted(Comparator.comparing(ProductSubList::getProductDate))
.collect(Collectors.toList()));
Error:
Required type: ProductSubList ; Provided:void
Part Answer which seems too long, is there a way to make this shorter?
if (Optional.of(mainProducts).map(MainProducts::getProductSubList).isPresent()) {
productSublist = mainProducts.getProductSubList().stream()
.sorted(Comparator.comparing(ProductSubList::getProductDate))
.collect(Collectors.toList());
}
Resource: How to avoid checking for null values in method chaining?
Solution
Seems you're looking for something like this:
List<ProductSubList> productSubList = Optional.ofNullable(mainProducts)
.map(MainProducts::getProductSubList)
.map(list -> list.stream()
.sorted(Comparator.comparing(ProductSubList::getProductDate))
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
Answered By - shmosel
Answer Checked By - Timothy Miller (JavaFixing Admin)