1. import java.time.Duration;
  2. import java.time.LocalDateTime;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class TimeAnomalyDetector {
  6. /**
  7. * Detects anomalies in a list of LocalDateTime values.
  8. *
  9. * @param timestamps A list of LocalDateTime timestamps.
  10. * @param anomalyThresholdDuration The duration (in minutes) considered anomalous.
  11. * @return A list of LocalDateTime timestamps flagged as anomalies.
  12. */
  13. public static List<LocalDateTime> detectAnomalies(List<LocalDateTime> timestamps, long anomalyThresholdDuration) {
  14. List<LocalDateTime> anomalies = new ArrayList<>();
  15. if (timestamps == null || timestamps.size() < 2) {
  16. return anomalies; // Not enough data to detect anomalies
  17. }
  18. for (int i = 1; i < timestamps.size(); i++) {
  19. LocalDateTime prevTimestamp = timestamps.get(i - 1);
  20. LocalDateTime currentTimestamp = timestamps.get(i);
  21. Duration duration = Duration.between(prevTimestamp, currentTimestamp);
  22. if (duration.toMinutes() > anomalyThresholdDuration) {
  23. anomalies.add(currentTimestamp); // Flag as anomaly
  24. }
  25. }
  26. return anomalies;
  27. }
  28. public static void main(String[] args) {
  29. // Example Usage
  30. List<LocalDateTime> timestamps = new ArrayList<>();
  31. timestamps.add(LocalDateTime.now().minusHours(2));
  32. timestamps.add(LocalDateTime.now().minusHours(1));
  33. timestamps.add(LocalDateTime.now());
  34. timestamps.add(LocalDateTime.now().plusHours(2));
  35. timestamps.add(LocalDateTime.now().plusHours(3));
  36. timestamps.add(LocalDateTime.now().plusHours(4));
  37. long anomalyThreshold = 2; // minutes
  38. List<LocalDateTime> anomalies = detectAnomalies(timestamps, anomalyThreshold);
  39. if (anomalies.isEmpty()) {
  40. System.out.println("No anomalies detected.");
  41. } else {
  42. System.out.println("Anomalies detected:");
  43. for (LocalDateTime anomaly : anomalies) {
  44. System.out.println(anomaly);
  45. }
  46. }
  47. }
  48. }

Add your comment