import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class TimeAnomalyDetector {
/**
* Detects anomalies in a list of LocalDateTime values.
*
* @param timestamps A list of LocalDateTime timestamps.
* @param anomalyThresholdDuration The duration (in minutes) considered anomalous.
* @return A list of LocalDateTime timestamps flagged as anomalies.
*/
public static List<LocalDateTime> detectAnomalies(List<LocalDateTime> timestamps, long anomalyThresholdDuration) {
List<LocalDateTime> anomalies = new ArrayList<>();
if (timestamps == null || timestamps.size() < 2) {
return anomalies; // Not enough data to detect anomalies
}
for (int i = 1; i < timestamps.size(); i++) {
LocalDateTime prevTimestamp = timestamps.get(i - 1);
LocalDateTime currentTimestamp = timestamps.get(i);
Duration duration = Duration.between(prevTimestamp, currentTimestamp);
if (duration.toMinutes() > anomalyThresholdDuration) {
anomalies.add(currentTimestamp); // Flag as anomaly
}
}
return anomalies;
}
public static void main(String[] args) {
// Example Usage
List<LocalDateTime> timestamps = new ArrayList<>();
timestamps.add(LocalDateTime.now().minusHours(2));
timestamps.add(LocalDateTime.now().minusHours(1));
timestamps.add(LocalDateTime.now());
timestamps.add(LocalDateTime.now().plusHours(2));
timestamps.add(LocalDateTime.now().plusHours(3));
timestamps.add(LocalDateTime.now().plusHours(4));
long anomalyThreshold = 2; // minutes
List<LocalDateTime> anomalies = detectAnomalies(timestamps, anomalyThreshold);
if (anomalies.isEmpty()) {
System.out.println("No anomalies detected.");
} else {
System.out.println("Anomalies detected:");
for (LocalDateTime anomaly : anomalies) {
System.out.println(anomaly);
}
}
}
}
Add your comment