1. import java.time.Duration;
  2. import java.time.Instant;
  3. import java.util.List;
  4. import java.util.ArrayList;
  5. public class TimeExporter {
  6. /**
  7. * Exports time differences as a list of strings.
  8. * @param startTimes A list of Instant objects representing start times.
  9. * @param endTimes A list of Instant objects representing end times.
  10. * @return A list of strings, where each string represents the duration
  11. * between the corresponding start and end time. Returns an empty list
  12. * if input lists are null or have different sizes.
  13. */
  14. public static List<String> exportTimeDifferences(List<Instant> startTimes, List<Instant> endTimes) {
  15. if (startTimes == null || endTimes == null || startTimes.size() != endTimes.size()) {
  16. return new ArrayList<>(); // Return empty list for invalid input
  17. }
  18. List<String> results = new ArrayList<>();
  19. for (int i = 0; i < startTimes.size(); i++) {
  20. Duration duration = Duration.between(startTimes.get(i), endTimes.get(i));
  21. results.add(duration.toString()); // Convert Duration to string
  22. }
  23. return results;
  24. }
  25. public static void main(String[] args) {
  26. //Example Usage
  27. List<Instant> startTimes = new ArrayList<>();
  28. startTimes.add(Instant.now());
  29. startTimes.add(Instant.now());
  30. startTimes.add(Instant.now());
  31. List<Instant> endTimes = new ArrayList<>();
  32. endTimes.add(Instant.now().plusSeconds(5));
  33. endTimes.add(Instant.now().plusSeconds(10));
  34. endTimes.add(Instant.now().plusSeconds(15));
  35. List<String> timeDifferences = exportTimeDifferences(startTimes, endTimes);
  36. for (String diff : timeDifferences) {
  37. System.out.println(diff);
  38. }
  39. }
  40. }

Add your comment