Delete up to 1000 S3 objects at once in Java (DeleteObjectsRequest)

Delete up to 1000 S3 objects at once in Java (DeleteObjectsRequest)

If you want to delete S3 objects all at once, you can use the DeleteObjectsRequest class to delete up to 1000 objects at once.

This class is recommended when deleting all objects at once, since deleting objects one at a time increases the number of useless communications.

However, since you can only delete a maximum of 1000 objects, you must loop to delete more than 1000 objects.

public class Hoge() {
  private final AmazonS3 s3;
  private final S3Config config; // Assuming you have S3 information
  public Integer deleteMultipleObjects(List<String> deleteTarget){
    Integer count = 0;
    int size = 1000;
    for (int i = 0; i < deleteTarget.size(); i += size) {
      List<String> list = new ArrayList<>(
        deleteTarget.subList(i, Math.min(i + size, deleteTarget.size()))
      String[] keyArray = list.toArray(new String[list.size()]);
      DeleteObjectsResult result
        = s3.deleteObjects(new DeleteObjectsRequest(config.getBucket()).withKeys(keyArray).withQuiet(false));
      count += result.getDeletedObjects().size();
    return count;