gpt4 book ai didi

java - 获得最高值和最低值时统一代码

转载 作者:行者123 更新时间:2023-12-02 01:00:56 25 4
gpt4 key购买 nike

我的 IDE 向我发出重复代码警告,现在我试图找出是否有任何方法可以统一或找到这两种方法的共同抽象,这两种方法在结构上非常相似,但执行相反的操作?我自己也想不通。谢谢

public double getLowestCurrencyRateInTheCurrentMonth(String baseCurrency, String targetCurrency) {
Map<String, Map<String, Double>> rates = getAllRatesInCurrentMonth(baseCurrency);
double lowestRate = Double.MAX_VALUE;
for(Map<String, Double> ratesByDate : rates.values()){
double baseCurrecyRateToTargetCurrency = ratesByDate.get(targetCurrency);
if(baseCurrecyRateToTargetCurrency < lowestRate){
lowestRate = baseCurrecyRateToTargetCurrency;
}
}
return lowestRate;
}

public double getHighestCurrencyRateInTheCurrentMonth(String baseCurrency, String targetCurrency) {
Map<String, Map<String, Double>> rates = getAllRatesInCurrentMonth(baseCurrency);
double highestRate = Double.MIN_VALUE;
for(Map<String, Double> ratesByDate : rates.values()){
double baseCurrecyRateToTargetCurrency = ratesByDate.get(targetCurrency);
if(baseCurrecyRateToTargetCurrency > highestRate){
highestRate = baseCurrecyRateToTargetCurrency;
}
}
return highestRate;
}

最佳答案

在我看来,其中有很多不必要的代码。您可以使用 Streams 以更好的方式实现相同的目的。它看起来像这样:

public double getHighestCurrencyRateInTheCurrentMonth(String baseCurrency, String targetCurrency, String variant) {
Map<String, Map<String, Double>> rates = getAllRatesInCurrentMonth(baseCurrency);
DoubleStream doubleStream = rates.values().stream()
.mapToDouble(entry -> entry.get(targetCurrency));
OptionalDouble result = variant.equals("max") ? doubleStream.max() : doubleStream.min();
return result.orElse(0);
}

关于java - 获得最高值和最低值时统一代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60653302/

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