Java Thread Filtering

Hello, I have a dtos list that has a flag. I need to filter them and return.

The logic is that if there are two elements in the list and one of them is deleted, I retrieve the unused one, but if there is only one element and is deleted, I return it.

So basically the 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 change the pipeline Streamto implement the desired logic?

+4
source share
3 answers

This can be done by sorting by getIsDeleted:

existingItems.stream()
             .sorted( Comparator.comparing(Item::getIsDeleted ) )
             .findFirst()
             .orElseGet(Item::new);

This solution assumes that it existingItemscontains a small number of elements.

+5
source

List orElse:

existingItems.stream()
             .filter(e -> !e.getIsDeleted())
             .findAny()
             .orElse(existingItems.isEmpty() ? new Item() : existingItems.get(0));
+7

. @Danjo. .

existingItems.stream().sorted(Comparator.comparing(Item::getIsDeleted)
  .thenComparing(Comparator.comparing(Item::getValidFrom)))
             .findFirst()
             .orElse(new Item());
+3
source

Source: https://habr.com/ru/post/1681169/


All Articles