1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class MaintenanceTaskAggregator {
  4. private static final Logger logger = Logger.getLogger(MaintenanceTaskAggregator.class);
  5. public static Map<String, Integer> aggregateTaskValues(Map<String, String> taskData) {
  6. // Initialize a map to store the aggregated values.
  7. Map<String, Integer> aggregatedValues = new HashMap<>();
  8. if (taskData == null) {
  9. logger.warn("Task data is null. Returning empty map.");
  10. return aggregatedValues;
  11. }
  12. // Iterate through the task data.
  13. for (Map.Entry<String, String> entry : taskData.entrySet()) {
  14. String fieldName = entry.getKey();
  15. String fieldValue = entry.getValue();
  16. // Validate that the field is not empty.
  17. if (fieldValue != null && !fieldValue.trim().isEmpty()) {
  18. try {
  19. // Attempt to convert the field value to an integer.
  20. int value = Integer.parseInt(fieldValue);
  21. // Aggregate the value.
  22. aggregatedValues.put(fieldName, aggregatedValues.getOrDefault(fieldName, 0) + value);
  23. logger.debug("Aggregated value for field '{}': {}", fieldName, value);
  24. } catch (NumberFormatException e) {
  25. logger.warn("Invalid value for field '{}': '{}'. Skipping.", fieldName, fieldValue);
  26. }
  27. } else {
  28. logger.debug("Skipping empty or null value for field '{}'.", fieldName);
  29. }
  30. }
  31. return aggregatedValues;
  32. }
  33. // Simple Logger class for demonstration. Replace with a real logger in production.
  34. private static class Logger {
  35. private static final String LOG_LEVEL = "INFO";
  36. public static LoggergetLogger(Class<?> clazz) {
  37. return new LoggerImpl(clazz);
  38. }
  39. private LoggerImpl(Class<?> clazz) {
  40. // Placeholder for a real logger implementation.
  41. }
  42. }
  43. private static class LoggerImpl {
  44. private final Class<?> clazz;
  45. public LoggerImpl(Class<?> clazz) {
  46. this.clazz = clazz;
  47. }
  48. public void debug(String message) {
  49. System.out.println("[DEBUG] " + message);
  50. }
  51. public void warn(String message) {
  52. System.out.println("[WARN] " + message);
  53. }
  54. }
  55. public static void main(String[] args) {
  56. // Example Usage
  57. Map<String, String> taskData = new HashMap<>();
  58. taskData.put("bolts_tightened", "10");
  59. taskData.put("wires_replaced", "5");
  60. taskData.put("lubricant_applied", "2.5"); // will be truncated to 2
  61. taskData.put("filters_changed", "3");
  62. taskData.put("missing_parts", ""); //Empty value
  63. taskData.put("unnecessary_field", "abc"); //Invalid value
  64. taskData.put("bolts_tightened", "5"); //Update existing field
  65. Map<String, Integer> aggregated = aggregateTaskValues(taskData);
  66. System.out.println("Aggregated values: " + aggregated);
  67. }
  68. }

Add your comment