Jack
Jack

Reputation: 1

How to iterate element in a method after converting to List?

I have the following endpoint:

public void save(@Valid @RequestBody SaveRequest request) {
    demoService.save(request);
}

In SaveRequest, I pass a single productUuid as shown below.

@Data
public class SaveRequest {

    private UUID productUuid;

    private DetailsRequest detailsRequest;
}

Here is my service method:

public void save(final SaveRequest request) {
    detailService.getDetails(request.getProductUuid());

    // code omitted
}

What I want to do is; I just want to pass productUuid as a list instead of single element. private List<UUID> productUuid;

I thought that I can call the service method for each productUuid in the SaveRequest, instead of modifying the service method by using a similar approach to the following. Then I call this methıd from the Controller instead of the save methof of the service.

public void saveList(final SaveRequest request) {
    request.getProductUuidList().stream()
        .map(this::save)
        .collect(Collectors.toList());
}

But I could not use it. So, how should I fix this issue? If it is good approach to use saveList methood and call save method for each productUuid in the SaveRequest, it may be better to use it without changing the save method.

Upvotes: 1

Views: 90

Answers (1)

thinkgruen
thinkgruen

Reputation: 1

Updating the answer now. You were correct with your last answer, because Streams usually expect you to do something with what is inside (in your case UUIDs).

If you don't want to have a Consumer for UUIDs, you can use a for loop:

public void saveList(final SaveRequest request) {
  for (UUID uuid: request.getProductUuidList()) {
    save(request);
  }
}

and if you need the UUID that is currently being iterated, change the save method to accept a UUID as an argument

public void saveList(final SaveRequest request) {
  for (UUID uuid: request.getProductUuidList()) {
    save(uuid, request);
  }
}

As you can see, the last method has a consumer for UUIDs now, so it can also be done using streams:

public void saveList(final SaveRequest request) {
  request.getProductUuidList().stream().forEach(
    uuid -> save(uuid, request);
  )
}

Using stream() here is optional, but can provide you with helpful features, such as filters.

Upvotes: 2

Related Questions