I need to find a method (using streams) to return a Map<Category,Optional<ToDo>
, which help me group an ArrayList
and give me a ToDo
object with the highest priority
of each category
.
public record ToDo(String name, Category category,
int priority, LocalDate date) {}
public enum Category { HOME, WORK }
An example of the input data:
List<ToDo> todo = List.of(
new ToDo("Eat", Category.HOME, 1, LocalDate.of(2022, 8, 29)),
new ToDo("Sleep", Category.HOME, 2, LocalDate.of(2022, 8, 30)),
new ToDo("Learn", Category.WORK, 2, LocalDate.of(2022, 9, 3)),
new ToDo("Work", Category.WORK, 3, LocalDate.of(2022, 10, 3))
);
And in the end, I want to have something like this as a result:
{HOME=[ToDo{Description='Eat', category=HOME, priority=1, deadline=2022-08-29},
WORK=[ToDo{Description='Learn', category=WORK, priority=2, deadline=2022-09-03]}
I was trying to use
.collect(Collectors.groupingBy(p -> p.getCategory()));
and
.sorted(Comparator.comparing(ToDo::getPriority)).findFirst();
But I can't do it in a single method and get Optional
as a result. How can I resolve this problem?