Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write expression in java8?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 for Duration. So you must use reduce.
  • You want to distinguish between a Duration.ZERO found, and nothing found.

For durations I think you could do without the use of null.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading