gpt4 book ai didi

Java TreeMap 获取最小值和最大值

转载 作者:行者123 更新时间:2023-11-30 07:46:24 26 4
gpt4 key购买 nike

我有这样的 TreeMap。在城镇中进行一些输入后,如何获得城镇温度的最小值和最大值?我不会复制在 towns 中填写一些值的代码,因为它工作正常。

Map<String, Town> towns = new TreeMap<>();

Town.class是这样的。

public class Town {

private int temperature;
private int rainfall;
private int windPower;
private Downwind downwind;

public Town(int temperature, int rainfall, int windPower, Downwind downwind) {
this.temperature = temperature;
this.rainfall = rainfall;
this.windPower = windPower;
this.downwind = downwind;
}

public int getTemperature() {
return temperature;
}

public void setTemperature(int temperature) {
this.temperature = temperature;
}

public int getRainfall() {
return rainfall;
}

public void setRainfall(int rainfall) {
this.rainfall = rainfall;
}

public int getWindPower() {
return windPower;
}

public void setWindPower(int windPower) {
this.windPower = windPower;
}

public Downwind getDownwind() {
return downwind;
}

public void setDownwind(Downwind downwind) {
this.downwind = downwind;
}

最佳答案

最简单的:

Optional<Town> maybeMinTown = towns.values().stream()
.min(Comparator.comparing(Town::getTemperature));

Town minTown = maybeMinTown.get(); // throws NoSuchElementException when towns map is empty

max 相同- 您只需要使用max而不是min .

更新

要获得刚好温度,您可以 map Town到温度然后调用min/max :

final OptionalInt min = towns.values().stream()
.mapToInt(Town::getTemperature)
.min();

min.getAsInt(); // or you can call min.orElseGet(some_lowest_value)

OptionalInt int 相同什么Optional<Town>用于Town .

关于Java TreeMap 获取最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882150/

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