I’m trying to write this function with java 8 , but i didn’t succeeded.
This is my code :
private LocalTime getAbsenceParJour(List<test> tests) {
LocalTime absenceParJourTime = null;
Duration sum = Duration.ZERO;
for (test perPrestation : tests) {
if (perPrestation.getTypeContactLibre().equalsIgnoreCase("absence")) {
Duration duration = Duration.between(perPrestation.getHeureDebut(), perPrestation.getHeureFin());
sum = sum.plus(duration);
}
}
if (sum != null) {
long m = sum.toMinutes() % 60;
long s = sum.toHours() % 60;
absenceParJourTime = LocalTime.of(Long.valueOf(s).intValue(), Long.valueOf(m).intValue());
}
return absenceParJourTime;
}
where test is a class java this is :
public class Prestation {
private LocalTime heureDebut;
private LocalTime heureFin;
private String typeContactLibre;
}
Any help thanks in advance.
>Solution :
private LocalTime getAbsenceParJour(List<test> tests) {
Duration sum = tests.stream()
.filter(P-> P.getTypeContactLibre().equalsIgnoreCase("absence"))
.reduce(null, (sum, p) ->
(sum == null ? Duration.ZERO : sum)
.plus(Duration.between(p.getHeureDebut(), p.getHeureFin()));
LocalTime absenceParJourTime = null;
if (sum != null) {
int m = (int)(sum.toMinutes() % 60);
int s = (int)(sum.toHours() % 60);
absenceParJourTime = LocalTime.of(s, m);
}
return absenceParJourTime;
}
Use of Stream is tricky here:
- There is a
.sum
but not forDuration
. So you must usereduce
. - You want to distinguish between a Duration.ZERO found, and nothing found.
For durations I think you could do without the use of null.