Set<String> response = null;
Set<String> success = null;
for (String country : countrys) {
response = service.method(country);
if (response != null) {
success = response;
}
}
Here service.method
returns a Set<String>
. I want to add the response of each loop to the success Set.
Now, this code is just storing the response of the last loop in success. Can someone please help with this at the earliest?
CodePudding user response:
You could use the addAll(Collection<? extends E> c)
method (see spec):
Set<String> response = null;
Set<String> success = new HashSet<>();
for (String country : countrys) {
response = service.method(country);
if (response != null) {
success.addAll(response);
}
}
Keep in mind that you will want to initialize success
as an empty set (e.g. a HashSet
) first. Otherwise you will run into a NullPointerException
.