[英]How to get the object that has the maximum value for multiple attributes using a stream?
[英]Java Get maximum value of Set with attributes using a mapper
我有個問題。 我正在嘗試創建一個 function ,它返回Set<Measurement>
中給定屬性的最大值。 這是我現在擁有的 function:
public Map<Integer,Double> annualMaximumTrend(Function<Measurement,Double> mapper) {
Map<Integer, Double> maximumValue = new LinkedHashMap<>();
int startYear = determineStartYear();
for (int year = startYear; year <= LocalDate.now().getYear(); year++) {
LocalDate startDate = LocalDate.of(year - 1, 12, 31);
LocalDate endDate = LocalDate.of(year + 1, 1, 1);
Set<Measurement> stationAverages = new HashSet<>();
for (Station station : stations.values()) {
stationAverages.addAll(station
.getMeasurements()
.stream()
.filter(m -> m.getDate().isAfter(startDate) &&
m.getDate().isBefore(endDate) &&
!Double.isNaN(mapper.apply(m))
).collect(Collectors.toSet()));
}
OptionalDouble maximum = stationAverages.stream().mapToDouble(Measurement::getMaxTemperature).max();
if (maximum.isPresent())
maximumValue.put(year, maximum.getAsDouble());
}
return maximumValue;
}
但是我需要確定maximum
差異,因為我需要在某處使用mapper.apply()
而不是Measurement::getMaxTemperature
,因為該映射器決定了我想要哪個屬性的最大值。 我需要如何使用映射器?
您可以使用 lambda:
stationAverages.stream().mapToDouble(m -> mapper.apply(m)).max();
如果mapper
是ToDoubleFunction<Measurement>
你可以直接將它傳遞給mapToDouble()
。 因為它不是你需要在另一個函數/lambda 中調用它,例如mapToDouble(m -> mapper.apply(m))
。
或者,使用map(mapper).max(Comparator.naturalOrder())
來獲得Optional<Double>
。
但是,請注意,您已經有 2 個內部循環,其中一個不是必需的:
您可以在一個 go 中完成所有操作:
Optional<Double> max = stations.values().stream()
.flatMap(station -> station
.getMeasurements()
.stream()
.filter(m -> m.getDate().isAfter(startDate) &&
m.getDate().isBefore(endDate)
)
.map(mapper)
.filter(v -> !Double.isNaN(v))
)
.max(Comparator.naturalOrder());
實際上,您甚至可以在一個 go 中完成所有操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.