如何对对象属性进行数学运算?

时间:2020-03-10 18:32:24

标签: java java-8 java-stream

我有天气值为List<Weather> weatherList = new ArrayList();的对象列表

在列表上,我有两个对象:

{
    "latitude": 13.699444,
    "longitude": 12.676667,
    "timezone": "",
    "daily": {
        "data": [
            {
                "time": 1586037600,
                "sunriseTime": 1586059620,
                "sunsetTime": 1586107860,
                "moonPhase": 0.41,
                "temperatureHigh": 8.36,
                "temperatureHighError": 3.58,
                "temperatureLow": 3.72,

            }
        ]
    },
    "offset": 2
}

{
    "latitude": 11.699444,
    "longitude": 10.676667,
    "timezone": "",
    "daily": {
        "data": [
            {
                "time": 1586037600,
                "sunriseTime": 1586059620,
                "sunsetTime": 1586107860,
                "moonPhase": 0.41,
                "temperatureHigh": 12.36,
                "temperatureHighError": 6.58,
                "temperatureLow": 3.72,

            }
        ]
    },
    "offset": 2
}

我当然有所有的获取器和设置器。 我需要拾取具有较大值(temperatureHigh / temperatureLow)/ 2的该对象。 我尝试过

Double resultNumber;
for(Weather weather:  weatherList){
     resultNumber = ((weather.getDaily().getData().get(0).getTemperatureLow()/weather.getDaily().getData().get(0).getTemperatureHigh())/2);
//and here I got result for only one object
}

我应该怎么做?我应该补充说:Map<resultNumber,WeatherObject>吗?得到我的价值? 还是可以选择在此处使用流和lambda?

1 个答案:

答案 0 :(得分:1)

您可以只声明另一个存储当前值(temperatureHigh / temperatureLow)/ 2的变量。然后,将其与您存储的resultNumber进行比较。如果此临时数字较大,则将resultNumber和resultWeather都更新为当前值和天气。

Double temp;
Double resultNumber; 
Weather resultWeather; 
for(Weather weather:  weatherList){
    temp = ((weather.getDaily().getData().get(0).getTemperatureLow()/weather.getDaily().getData().get(0).getTemperatureHigh())/2);
    if(resultNumber == null || Double.compare(resultNumber,temp) < 0) {
        resultNumber = temp;
        resultWeather = weather;
    }
}
//at this point resultWeather holds the weather with the highest value

或者如果weatherList中只有两个天气,则可以只执行if else语句来比较两个天气的值,然后将较大值的天气存储到​​另一个天气对象中。

double value1 = weatherList.get(0).(the operation to get the value for the first weather);
double value2 = weatherList.get(1).(the operation to get the value for the other weather);
Weather resultWeather;
if(value1 > value2){
    resultWeather = weatherList.get(0);
}
else{
    resultWeather = weatherList.get(1);
}
//at this point resultWeather holds the weather with the higher value of the two


相关问题