Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the join result for an empty collection

Tags:

guava

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?

like image 276
SPIRiT_1984 Avatar asked Nov 28 '14 12:11

SPIRiT_1984


1 Answers

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.

like image 122
Pavel Parshin Avatar answered Oct 30 '22 03:10

Pavel Parshin