SPIRiT_1984
SPIRiT_1984

Reputation: 2787

What is the join result for an empty collection

I'm wondering, how exactly will Joiner.join behave if it is given an empty collection:

Joiner.on(",").join(new ArrayList());

I wonder, what is the expected behavior here. Will it return an empty string or a null? Or it depends on the platform and implementation of the library?

Upvotes: 5

Views: 7697

Answers (1)

Pavel Parshin
Pavel Parshin

Reputation: 517

Well, check source:

public String join(Iterable<? extends Entry<?, ?>> entries) {
  return join(entries.iterator());
}

Next:

public String join(Iterator<? extends Entry<?, ?>> entries) {
  return appendTo(new StringBuilder(), entries).toString();
}

And finally (skip one method):

public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts) throws IOException {
  checkNotNull(appendable);
  if (parts.hasNext()) {
    ...
  }
  return appendable;
}

If your collection is empty appendTo() will return empty StringBuilder. So, result is empty string.

Upvotes: 13

Related Questions