I have this kind of a TreeMap. How can i get minimum and maximum values for town temperature after i make some entries in towns
? I do not copy the code where i fill in some values in towns
because it works fine.
Map<String, Town> towns = new TreeMap<>();
The Town.class is like this.
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;
}
The simplest:
Optional<Town> maybeMinTown = towns.values().stream()
.min(Comparator.comparing(Town::getTemperature));
Town minTown = maybeMinTown.get(); // throws NoSuchElementException when towns map is empty
the same for max
- you only need to use max
instead of min
.
UPDATE
To get just temperature you can map
Town
to temperature and then call min
/ max
:
final OptionalInt min = towns.values().stream()
.mapToInt(Town::getTemperature)
.min();
min.getAsInt(); // or you can call min.orElseGet(some_lowest_value)
OptionalInt
is the same for int
what Optional<Town>
is for Town
.
If you are not in Java 8, you have to order the Map by value to achieve that, maybe something like this
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;
}
When you create your TreeMap, pass an instance of this comparator class
towns = sortByValues(towns);
After that, you will have the maximun value at position 0 and the minimun in the last element.
UPDATE
Change the code in order to compile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.