如何根据Java 8 Stream过滤器的输出计算百分比

时间:2014-07-21 20:36:47

标签: java java-8 lambda

我想获取一份工作列表(称为resultStream)并计算完全完成的工作百分比。

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

    // Getter and setter and constructor.
}

该列表包含以下内容:

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

这是我到目前为止的代码:

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

这将返回一个HashMap(Date,Long),其中包含以下内容:
    今天,2
    昨天,1

我实际上想要以下结果:
    今天,66%
    昨天,100%

提前致谢。

1 个答案:

答案 0 :(得分:7)

平均为双倍可以这样做:

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);
}

作为字符串:

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);
}