[英]Java Stream Maximum Value From Average
我必须得到最高平均温度的国家名称。
我用以下来获得平均温度
this.getTemperatures()
.stream()
.collect(Collectors.groupingBy(Temperature::getCountry,
Collectors.averagingDouble(Temperature::getAverageTemperature)))
如何从此平均温度列表中获取最大或最小平均国家/地区名称?
我不太喜欢这个,因为很多代码都会重复,但它会起作用。 如果不使代码变得更糟,我无法找到避免重复的方法。
这也会迭代所有的地图条目两次,但鉴于只有195个国家/地区,我们谈论的是最多195次额外迭代(如果您对每一个都进行了测量),这对于CPU来说是完全可以忽略不计的数量。
String max = countryToAvgTemp.entrySet().stream() //stream all entries
.max(Map.Entry.comparingByValue()) //get the max by comparing entry value
.map(Map.Entry::getKey) //grab the key
.orElseThrow(() -> new RuntimeException("No max")); //e.g. if the list is empty
String min = countryToAvgTemp.entrySet().stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElseThrow(() -> new RuntimeException("No min"));
如果你只想迭代一次,你可以编写自己的收集器,它返回类似MinMax<String>
东西。 我写了一个,但代码不是很好。 最好保持简单。
使用
Collections.min(temperatureMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getValue()
和
Collections.max(temperatureMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getValue()
如果你想获得最大或最小平均国家名称,你可以对温度列表进行排序,然后得到第一个和最后一个元素。但是你的工作不需要排序列表,这不是一个好方法,@ Michael的方法非常适合您。
List<Temperature> temperatures = Arrays.asList(
new Temperature("a",10),
new Temperature("b",11),
new Temperature("c",12),
new Temperature("d",13),
new Temperature("e",14),
new Temperature("f",15),
new Temperature("g",16),
new Temperature("h",17));
temperatures = temperatures.stream().sorted(new Comparator<Temperature>() {
@Override
public int compare(Temperature o1, Temperature o2) {
return (int) (o1.getAverageTemperature() - o2.getAverageTemperature());
}
}).collect(Collectors.toList());
String min = temperatures.get(0).getCountry();
String max = temperatures.get(temperatures.size()-1).getCountry();
您可以尝试DoubleSummaryStatistics:
this.getTemperatures()
.stream()
.collect(Collectors.groupingBy(Temperature::getCountry,
Collectors.summarizingDouble(Temperature::getAverageTemperature)));
这将返回一张地图:
Map<Country, DoubleSummaryStatistics>
因此,使用DoubleSummaryStatistics,您可以获得每个国家/地区的计数,总和,最小值,最大值,平均值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.