javacollectionsjava-streamspotify-docker-client

Java 8 : Order a Collection by stream representation date in ascending way using collections streams


I'm working with DockerClient and I have a collection from images, I need to delete all of them, but not the latest one, so I wanted to sort the collection in ascending way, I have a created field which is a string with the number representation of the date as 1632912516.

I tried the next:

    public void checkingTest() throws DockerException, InterruptedException {
      try {
      List<com.spotify.docker.client.messages.Image> sortedImages = getImages();

      sortedImages.stream()
          .filter(img -> !img.id().equals(sortedImages.get(sortedImages.size() - 1).id()))
          .forEach(img -> {
            try {
              dockerClient.removeImage(img.id());
            }
            catch (DockerException e) {
              e.printStackTrace();
            }
            catch (InterruptedException e) {
              e.printStackTrace();
            }
          });
    }
    catch (DockerCertificateException e) {
      e.printStackTrace();
    }
  }

  private List<com.spotify.docker.client.messages.Image> getImages()
      throws DockerCertificateException, DockerException, InterruptedException
  {
    final DockerClient dockerClient =
        DefaultDockerClient.fromEnv().connectTimeoutMillis(TimeUnit.SECONDS.toMillis(3)).build();

    return dockerClient.listImages()
        .stream()
        .filter(image -> image.labels() != null && image.labels().containsKey("image"))
        .sorted((o1, o2) -> o2.created().compareTo(o1.created()))
        .collect(
            Collectors.toList());
  }

But I saw, that in the getImages method the collection is not sorted, so I think I need to convert the created field to something different of a String to achieve this.

Any ideas?


Solution

  • Collections.max()

    You don’t need to sort all of your images to find the newest. Collections.max() can do that. Simplified code to illustrate my point:

        List<Image> unsortedImages = // …;
        if (! unsortedImages.isEmpty()) {
            Id latestId = Collections.max(unsortedImages,
                            Comparator.comparingLong(img -> Long.parseLong(img.created())))
                   .id();
             // Proceed with deleting as in your code
        }
    

    I understand that Image.created() returns a String holding a Unix timestamp (number of seconds since the Unix epoch in 1970).