user3663882
user3663882

Reputation: 7357

How to iterate over a non-empty string?

I need to iterate over some String if it's not empty. 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. How can I avoid that?

Upvotes: 0

Views: 327

Answers (3)

anonymouse
anonymouse

Reputation: 51

1) Collections.emptyList() solves the problem of creating a new object every time (not that you should worry about such micro-optimizations).

2) You don't need the iterator. Instead, use the code below:

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

Upvotes: 1

Rajesh
Rajesh

Reputation: 2155

Validate empty before iterating:

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

Upvotes: 1

Turing85
Turing85

Reputation: 20185

You could enter the loop only 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>(); and iterate over this list instead.

Upvotes: 1

Related Questions