Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java streams filtering

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?

like image 655
DanJo Avatar asked Dec 04 '22 21:12

DanJo


2 Answers

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));
like image 111
Eran Avatar answered Dec 11 '22 15:12

Eran


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.

like image 32
WW. Avatar answered Dec 11 '22 15:12

WW.