简体   繁体   English

如何遍历非空字符串?

[英]How to iterate over a non-empty string?

I need to iterate over some String if it's not empty. 如果它不为空,我需要遍历一些String。 I mean this: 我的意思是:

for (String email : partnerEmails.isEmpty() ? new ArrayList<String>()
                    : partnerEmails.split("\\s*,\\s*")) {
    selectedEmails.add(email);
}

The thing that I'm worried about is that I'm creating a new empty list which takes some resources and memory, and need to be garbage collected soon. 我担心的是,我正在创建一个新的空list ,该list需要一些资源和内存,并且需要尽快进行垃圾回收。 How can I avoid that? 我该如何避免呢?

You could enter the loop only if ((null != partnerEmails) && !partnerEmails.isEmpty()) . if ((null != partnerEmails) && !partnerEmails.isEmpty())时才可以进入循环。 If you want to keep your loop, you could define a private static ArrayList<String> EMPTY_LIST = new ArrayList<String>(); 如果要保持循环,可以定义一个private static ArrayList<String> EMPTY_LIST = new ArrayList<String>(); and iterate over this list instead. 然后遍历此列表。

Validate empty before iterating: 在迭代之前验证空值:

if (!partnerEmails.isEmpty())
    for (String email : partnerEmails.split("\\s*,\\s*"))
        selectedEmails.add(email);  

1) Collections.emptyList() solves the problem of creating a new object every time (not that you should worry about such micro-optimizations). 1) Collections.emptyList()解决了每次创建新对象的问题(而不是您应该担心这种微优化)。

2) You don't need the iterator. 2)您不需要迭代器。 Instead, use the code below: 而是使用以下代码:

List<String> emails = partnerEmails.isEmpty()
                    ? Collections.emptyList()
                    : Arrays.asList(partnerEmails.split("\\s*,\\s*"));
selectedEmails.addAll(emails);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM