gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:09:34 25 4
gpt4 key购买 nike

我想获取一个作业列表(称为 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%

提前致谢。

最佳答案

Average as double 可以这样做:

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

关于java - 如何根据 Java 8 Stream 过滤器的输出计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24874256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com