1. import java.util.ArrayList;
  2. import java.util.HashSet;
  3. import java.util.List;
  4. import java.util.Set;
  5. public class TimestampDeduplicator {
  6. /**
  7. * Removes duplicate timestamps from a list of timestamps.
  8. *
  9. * @param timestamps A list of timestamps (represented as long).
  10. * @return A new list containing only unique timestamps, preserving the original order.
  11. */
  12. public static List<Long> removeDuplicateTimestamps(List<Long> timestamps) {
  13. List<Long> uniqueTimestamps = new ArrayList<>(); // Store unique timestamps
  14. Set<Long> seenTimestamps = new HashSet<>(); // Keep track of seen timestamps
  15. for (Long timestamp : timestamps) {
  16. if (!seenTimestamps.contains(timestamp)) {
  17. uniqueTimestamps.add(timestamp); // Add to unique list if not seen before
  18. seenTimestamps.add(timestamp); // Mark as seen
  19. }
  20. }
  21. return uniqueTimestamps;
  22. }
  23. public static void main(String[] args) {
  24. // Example Usage
  25. List<Long> timestamps = new ArrayList<>();
  26. timestamps.add(1678886400000L);
  27. timestamps.add(1678886400000L);
  28. timestamps.add(1678972800000L);
  29. timestamps.add(1678972800000L);
  30. timestamps.add(1679059200000L);
  31. List<Long> uniqueTimestamps = removeDuplicateTimestamps(timestamps);
  32. System.out.println("Original timestamps: " + timestamps);
  33. System.out.println("Unique timestamps: " + uniqueTimestamps);
  34. }
  35. }

Add your comment