我正在尝试将以下Java代码转换为Java 8。我编写了以下代码来计算平均温度。
public static double calculateTemps(String country, Map<String, List<Temperatures>> tempMap) {
double temp = 0.0f;
int count = 0;
if (country.equalsIgnoreCase("India")) {
for (Map.Entry<String, List<Temperatures>> m : tempMap.entrySet()) {
for (Temperatures t : m.getValue()) {
temp = temp + t.getTemp();
count++;
}
}
}
System.out.println(count);
return temp / count;
}以上代码运行良好。现在,我正在尝试将它转换为Java 8。
public static double calculateTemps(String country, Map<String, List<Temperatures>> tempMap) {
double temp = 0.0f;
int count = 0;
tempMap.entrySet().stream().filter(temps -> temps.getKey()
.equalsIgnoreCase("India"))
.forEach(temps -> {
temp = temp + temps.getValue();
}).collect(Collectors.toSet());
}我认为地图在这里更适合,但是在我考虑了一些关于堆栈溢出的问题之后,每个问题在这里都更适合。不确定。有人能指点我一下吗?
发布于 2022-07-15 05:54:48
您的代码有多个问题:
您正在尝试向Temperatures.getTemp()
Temperatures对象,而不是试图在lambda中修改变量temp,但是temp实际上必须是您在void方法forEach上调用collect的最终
H 213G 214您可以使用DoubleStream的特性来计算平均值:
return tempMap.entrySet().stream()
.filter(temps -> temps.getKey().equalsIgnoreCase("India"))
.flatMap(temps -> temps.getValue().stream())
.mapToDouble(temp -> temp.getTemp())
.average().orElse(0.0);顺便说一句,filter条件与原始方法中使用的条件不同(根据country参数进行检查),但我保留了它与您最初的尝试不同。仔细检查它是否真的是你所需要的。
发布于 2022-07-15 05:54:18
你可以试试这个
public static double calculateTemps(String country, Map<String, List<Temperatures>> tempMap) {
return tempMap.entrySet()
.stream()
.filter(temps -> temps.getKey().equalsIgnoreCase("India"))
.flatMap(entry -> entry.getValue().stream())
.mapToDouble(Temperatures::getTemp)
.average()
.orElse(0.0);
}发布于 2022-07-15 05:57:21
你可以这样引用:
public static double calculateTemps(String country, Map<String, List<Temperatures>> tempMap) {
double temp = 0.0f;
int count = 0;
if (country.equalsIgnoreCase("India")) {
double result = tempMap.entrySet().stream()
.flatMap(entry -> entry.getValue().stream())
.mapToDouble(Temperatures::getTemp)
.average().orElse(0.0);
System.out.println(result);
}
return 0;
}https://stackoverflow.com/questions/72989464
复制相似问题