This is a very interesting question. The solution is not as easy as it looks to be. You have to divide the solution into multiple steps:
- Get the max value for each grouped
procedureName
based on the first dates in the List<Date>
.
- Compare the
Procedure
instances based on max Date
value from the Map<String, Date
created in the step one.
- If they are equal distinguish them by the name (ex. two times
Procedure 2
).
- If they are still equal, sort the
Procedure
instances based on their actual first date.
Here is the demo at: https://www.jdoodle.com/iembed/v0/Te.
Step 1
List<Procedure> procedures = ...
Map<String, Date> map = procedures.stream().collect(
Collectors.collectingAndThen(
Collectors.groupingBy(
Procedure::getProcedureName,
Collectors.maxBy(Comparator.comparing(s -> s.getProcedureDate().get(0)))),
s -> s.entrySet().stream()
.filter(e -> e.getValue().isPresent())
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().get().getProcedureDate().get(0)))));
.. explained: There is a simple way to get a Procedure
with maximum first date grouped by procedureName
.
Map<String, Optional<Procedure>> mapOfOptionalProcedures = procedures.stream()
.collect(Collectors.groupingBy(
Procedure::getProcedureName,
Collectors.maxBy(Comparator.comparing(o -> o.getProcedureDate().get(0)))));
However, the returned structure is a bit clumsy (Map<String, Optional<Procedure>>
), to make it useful and return Date
directly, there is a need of additional downstream collector Collectors::collectingAndThen
which uses a Function
as a result mapper:
Map<String, Date> map = procedures.stream().collect(
Collectors.collectingAndThen(
/* grouping part */,
s -> s.entrySet().stream()
.filter(e -> e.getValue().isPresent())
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().get().getProcedureDate().get(0)))));
... which is effectively the first snippet.
Steps 2, 3 and 4
Basically, sort by the maximum date for each group. Then sort by the name and finally by the actual first date.
Collections.sort(
procedures,
(l, r) -> {
int dates = map.get(r.getProcedureName()).compareTo(map.get(l.getProcedureName()));
if (dates == 0) {
int names = l.getProcedureName().compareTo(r.getProcedureName());
if (names == 0) {
return r.getProcedureDate().get(0).compareTo(l.getProcedureDate().get(0));
} else return names;
} else return dates;
}
);
Sorted result
Using the deprecated java.util.Date
according to your question, the sorted procedures
will have sorted items like your expected snippet (I have overrided the Procedure::toString
method)
@Override
public String toString() {
return procedureName + " " + procedureDate;
}
Procedure2 [Mon Jan 06 00:00:00 CET 2020]
Procedure2 [Fri Jan 03 00:00:00 CET 2020]
Procedure5 [Sun Jan 05 00:00:00 CET 2020, Thu Jan 02 00:00:00 CET 2020]
Procedure1 [Sat Jan 04 00:00:00 CET 2020]
Procedure1 [Wed Jan 01 00:00:00 CET 2020]
Procedure3 [Fri Jan 03 00:00:00 CET 2020]