Java Stream API: Filter JSON Data by Time Range and Calculate Sum of BigDecimal
To solve this problem, you can use the Java Stream API to filter the data based on the time range and calculate the sum of all the 'data' values using BigDecimal. Here's an example code snippet:
import org.json.JSONArray;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Assuming the 'list' variable contains the JSON array
JSONArray list = new JSONArray("[{"data": 0.1, "mon": 0.06, "dbs": 23.26, "time": "2023-09-18 00:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.36, "time": "2023-09-18 01:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.46, "time": "2023-09-18 02:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.56, "time": "2023-09-18 03:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.66, "time": "2023-09-18 04:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.76, "time": "2023-09-18 05:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.86, "time": "2023-09-18 06:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 23.96, "time": "2023-09-18 07:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.06, "time": "2023-09-18 08:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.16, "time": "2023-09-18 09:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.26, "time": "2023-09-18 10:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.36, "time": "2023-09-18 11:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.46, "time": "2023-09-18 12:59:59"}, {"data": 0.1, "mon": 0.06, "dbs": 24.56, "time": "2023-09-18 13:59:59"}]");
// Get the work time range from the configuration file
String workTime = "08:00:00-18:00:00";
String[] timeRange = workTime.split("-");
LocalTime startTime = LocalTime.parse(timeRange[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
LocalTime endTime = LocalTime.parse(timeRange[1], DateTimeFormatter.ofPattern("HH:mm:ss"));
// Filter the data based on the time range and calculate the sum of 'data' values
BigDecimal sum = list.toList().stream()
.map(JSONObject.class::cast)
.filter(json -> {
LocalTime time = LocalTime.parse(json.getString("time"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return time.isBefore(startTime) || time.isAfter(endTime);
})
.map(json -> new BigDecimal(json.getDouble("data")))
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("Sum of 'data' values: " + sum);
}
}
Make sure to replace {...} in the JSONArray constructor with the actual JSON data provided in your question.
原文地址: https://www.cveoy.top/t/topic/hxL3 著作权归作者所有。请勿转载和采集!