Hello I have a list of dtos which have flag is deleted. I need to filter them and return one.
The logic is that if there is two items in the list and one of them is deleted I fetch non deleted one, but if there is only one item and deleted then I return it.
So basically order is not deleted > deleted > new item.
List<Item> existingItems = service.getItems();
existingItems.stream().filter(e -> !e.getIsDeleted()).findAny().orElse(new Item());
How can I modify this Stream
pipeline to implement the required logic?
You can return the first element of the List
in orElse
:
existingItems.stream()
.filter(e -> !e.getIsDeleted())
.findAny()
.orElse(existingItems.isEmpty() ? new Item() : existingItems.get(0));
You can achieve this by sorting on getIsDeleted
:
existingItems.stream()
.sorted( Comparator.comparing(Item::getIsDeleted ) )
.findFirst()
.orElseGet(Item::new);
This solution assumes that existingItems
contains a small number of items.
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