繁体   English   中英

Java TreeMap获取最小值和最大值

[英]Java TreeMap get min and max values

我有这种TreeMap。 towns输入一些信息后,如何获得城镇温度的最小值和最大值? 我不会在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

UPDATE

为了让你可以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对于intOptional<Town>对于Town

如果您不是使用Java 8,则必须按值对Map进行排序才能实现这一点,也许像这样

public static Map<String, Town> sortByValues(final Map<String, Town> map) {
    Comparator<String> valueComparator =  new Comparator<String>() {
        public int compare(String k1, String k2) {
            if (map.get(k1).getTemperature() < map.get(k2).getTemperature()) {
                return 1;
            } else if (map.get(k1).getTemperature() == map.get(k2).getTemperature()) {
                return 0;
            } else {
                return -1;
            }
        }
    };
    Map<String, Town> sortedByValues = new TreeMap<String, Town>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

创建TreeMap时,传递此比较器类的实例

towns = sortByValues(towns);

之后,您将在位置0获得最大值,在最后一个元素中获得最小值。

UPDATE

更改代码以进行编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM