import java.util.HashMap;
import java.util.Map;
public class MaintenanceTaskAggregator {
private static final Logger logger = Logger.getLogger(MaintenanceTaskAggregator.class);
public static Map<String, Integer> aggregateTaskValues(Map<String, String> taskData) {
// Initialize a map to store the aggregated values.
Map<String, Integer> aggregatedValues = new HashMap<>();
if (taskData == null) {
logger.warn("Task data is null. Returning empty map.");
return aggregatedValues;
}
// Iterate through the task data.
for (Map.Entry<String, String> entry : taskData.entrySet()) {
String fieldName = entry.getKey();
String fieldValue = entry.getValue();
// Validate that the field is not empty.
if (fieldValue != null && !fieldValue.trim().isEmpty()) {
try {
// Attempt to convert the field value to an integer.
int value = Integer.parseInt(fieldValue);
// Aggregate the value.
aggregatedValues.put(fieldName, aggregatedValues.getOrDefault(fieldName, 0) + value);
logger.debug("Aggregated value for field '{}': {}", fieldName, value);
} catch (NumberFormatException e) {
logger.warn("Invalid value for field '{}': '{}'. Skipping.", fieldName, fieldValue);
}
} else {
logger.debug("Skipping empty or null value for field '{}'.", fieldName);
}
}
return aggregatedValues;
}
// Simple Logger class for demonstration. Replace with a real logger in production.
private static class Logger {
private static final String LOG_LEVEL = "INFO";
public static LoggergetLogger(Class<?> clazz) {
return new LoggerImpl(clazz);
}
private LoggerImpl(Class<?> clazz) {
// Placeholder for a real logger implementation.
}
}
private static class LoggerImpl {
private final Class<?> clazz;
public LoggerImpl(Class<?> clazz) {
this.clazz = clazz;
}
public void debug(String message) {
System.out.println("[DEBUG] " + message);
}
public void warn(String message) {
System.out.println("[WARN] " + message);
}
}
public static void main(String[] args) {
// Example Usage
Map<String, String> taskData = new HashMap<>();
taskData.put("bolts_tightened", "10");
taskData.put("wires_replaced", "5");
taskData.put("lubricant_applied", "2.5"); // will be truncated to 2
taskData.put("filters_changed", "3");
taskData.put("missing_parts", ""); //Empty value
taskData.put("unnecessary_field", "abc"); //Invalid value
taskData.put("bolts_tightened", "5"); //Update existing field
Map<String, Integer> aggregated = aggregateTaskValues(taskData);
System.out.println("Aggregated values: " + aggregated);
}
}
Add your comment