将响应添加到Set< string>

发布于 2025-01-19 12:46:03 字数 417 浏览 4 评论 0原文

Set<String> response = null;
Set<String> success = null;
for (String country : countrys) {

    response = service.method(country);

    if (response != null) {

        success = response;
    }
}

这里 service.method 返回一个 Set。我想将每个循环的响应添加到成功集中。

现在,这段代码只是存储最后一次成功循环的响应。 有人可以尽早帮忙解决这个问题吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光与爱终年不遇 2025-01-26 12:46:03

您可以使用 addAll(Collection c) 方法 (参见规范):

    Set<String> response = null;
    Set<String> success = new HashSet<>();
    for (String country : countrys) {

        response = service.method(country);

        if (response != null) {
            success.addAll(response);
        }
    }

请记住,您需要将 success 初始化为空集(例如 HashSet) 首先。否则,您将遇到 NullPointerException

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文