How to calculate percentage based on Java 8 Stream filter output

I want to take a list of tasks (called resultStream) and calculate the percentage of work completed in full.

public class Job {
    private Date date;
    private String success;

    // Getter and setter and constructor.
}

The list contains the following:

new Job("TODAY", "YES");
new Job("TODAY", "YES");
new Job("YESTERDAY", "YES");
new Job("TODAY", "NO");

Here is the code that I still have:

resultStream.stream().parallel().filter(result -> {
   if ("YES".contains(result.getSuccess())) {
       return true;         
   } else {
       return false;
   }
}).collect(groupingBy(Job::getDate, HashMap::new, counting()));

This returns me a HashMap (Date, Long) with the following:
  TODAY, 2
  YESTERDAYS, 1

I really want to get the following result:
  TODAY, 66%
  YESTERDAY, 100%

Thanks in advance.

+4
source share
1 answer

The average value of double can be performed as follows:

public static void main(final String... args) {
    final List<Job> jobs = new ArrayList<>();
    jobs.add(new Job(LocalDate.now(), "YES"));
    jobs.add(new Job(LocalDate.now(), "NO"));
    jobs.add(new Job(LocalDate.now(), "YES"));
    jobs.add(new Job(LocalDate.now()
            .minusDays(1), "YES"));

    final Map<LocalDate, Double> result = jobs.stream()
        .collect(
                    Collectors.groupingBy(Job::getDate,
                            Collectors.mapping(Job::getSuccess, Collectors.averagingDouble(success -> {
                                return "YES".equals(success) ? 1 : 0;
                            }))));

    // result = {2014-07-20=1.0, 2014-07-21=0.6666666666666666}
    System.out.println(result);
}

Like strings:

public static void main(final String... args) {
    final List<Job> jobs = new ArrayList<>();
    jobs.add(new Job(LocalDate.now(), "YES"));
    jobs.add(new Job(LocalDate.now(), "NO"));
    jobs.add(new Job(LocalDate.now(), "YES"));
    jobs.add(new Job(LocalDate.now()
            .minusDays(1), "YES"));

    final Map<LocalDate, String> result = jobs.stream()
            .collect(
                    Collectors.groupingBy(
                            Job::getDate,
                            Collectors.collectingAndThen(
                                    Collectors.mapping(Job::getSuccess, Collectors.averagingDouble(success -> {
                                        return "YES".equals(success) ? 1 : 0;
                                    })), avg -> String.format("%,.0f%%", avg * 100))));
    // result = {2014-07-20=100%, 2014-07-21=67%}
    System.out.println(result);
}
+7
source

All Articles