001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import java.io.IOException;
023import java.util.AbstractList;
024import java.util.Arrays;
025import java.util.Iterator;
026import java.util.Map;
027import java.util.Map.Entry;
028import org.checkerframework.checker.nullness.qual.Nullable;
029
030/**
031 * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a
032 * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns
033 * them as a {@link String}. Example:
034 *
035 * <pre>{@code
036 * Joiner joiner = Joiner.on("; ").skipNulls();
037 *  . . .
038 * return joiner.join("Harry", null, "Ron", "Hermione");
039 * }</pre>
040 *
041 * <p>This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are
042 * converted to strings using {@link Object#toString()} before being appended.
043 *
044 * <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining
045 * methods will throw {@link NullPointerException} if any given element is null.
046 *
047 * <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code
048 * useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner
049 * instance returned by the method. This makes joiners thread-safe, and safe to store as {@code
050 * static final} constants.
051 *
052 * <pre>{@code
053 * // Bad! Do not do this!
054 * Joiner joiner = Joiner.on(',');
055 * joiner.skipNulls(); // does nothing!
056 * return joiner.join("wrong", null, "wrong");
057 * }</pre>
058 *
059 * <p>See the Guava User Guide article on <a
060 * href="https://github.com/google/guava/wiki/StringsExplained#joiner">{@code Joiner}</a>.
061 *
062 * @author Kevin Bourrillion
063 * @since 2.0
064 */
065@GwtCompatible
066public class Joiner {
067  /** Returns a joiner which automatically places {@code separator} between consecutive elements. */
068  public static Joiner on(String separator) {
069    return new Joiner(separator);
070  }
071
072  /** Returns a joiner which automatically places {@code separator} between consecutive elements. */
073  public static Joiner on(char separator) {
074    return new Joiner(String.valueOf(separator));
075  }
076
077  private final String separator;
078
079  private Joiner(String separator) {
080    this.separator = checkNotNull(separator);
081  }
082
083  private Joiner(Joiner prototype) {
084    this.separator = prototype.separator;
085  }
086
087  /**
088   * Appends the string representation of each of {@code parts}, using the previously configured
089   * separator between each, to {@code appendable}.
090   */
091  @CanIgnoreReturnValue
092  public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException {
093    return appendTo(appendable, parts.iterator());
094  }
095
096  /**
097   * Appends the string representation of each of {@code parts}, using the previously configured
098   * separator between each, to {@code appendable}.
099   *
100   * @since 11.0
101   */
102  @CanIgnoreReturnValue
103  public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
104    checkNotNull(appendable);
105    if (parts.hasNext()) {
106      appendable.append(toString(parts.next()));
107      while (parts.hasNext()) {
108        appendable.append(separator);
109        appendable.append(toString(parts.next()));
110      }
111    }
112    return appendable;
113  }
114
115  /**
116   * Appends the string representation of each of {@code parts}, using the previously configured
117   * separator between each, to {@code appendable}.
118   */
119  @CanIgnoreReturnValue
120  public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException {
121    return appendTo(appendable, Arrays.asList(parts));
122  }
123
124  /** Appends to {@code appendable} the string representation of each of the remaining arguments. */
125  @CanIgnoreReturnValue
126  public final <A extends Appendable> A appendTo(
127      A appendable, @Nullable Object first, @Nullable Object second, Object... rest)
128      throws IOException {
129    return appendTo(appendable, iterable(first, second, rest));
130  }
131
132  /**
133   * Appends the string representation of each of {@code parts}, using the previously configured
134   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
135   * Iterable)}, except that it does not throw {@link IOException}.
136   */
137  @CanIgnoreReturnValue
138  public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) {
139    return appendTo(builder, parts.iterator());
140  }
141
142  /**
143   * Appends the string representation of each of {@code parts}, using the previously configured
144   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
145   * Iterable)}, except that it does not throw {@link IOException}.
146   *
147   * @since 11.0
148   */
149  @CanIgnoreReturnValue
150  public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) {
151    try {
152      appendTo((Appendable) builder, parts);
153    } catch (IOException impossible) {
154      throw new AssertionError(impossible);
155    }
156    return builder;
157  }
158
159  /**
160   * Appends the string representation of each of {@code parts}, using the previously configured
161   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
162   * Iterable)}, except that it does not throw {@link IOException}.
163   */
164  @CanIgnoreReturnValue
165  public final StringBuilder appendTo(StringBuilder builder, Object[] parts) {
166    return appendTo(builder, Arrays.asList(parts));
167  }
168
169  /**
170   * Appends to {@code builder} the string representation of each of the remaining arguments.
171   * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not
172   * throw {@link IOException}.
173   */
174  @CanIgnoreReturnValue
175  public final StringBuilder appendTo(
176      StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) {
177    return appendTo(builder, iterable(first, second, rest));
178  }
179
180  /**
181   * Returns a string containing the string representation of each of {@code parts}, using the
182   * previously configured separator between each.
183   */
184  public final String join(Iterable<?> parts) {
185    return join(parts.iterator());
186  }
187
188  /**
189   * Returns a string containing the string representation of each of {@code parts}, using the
190   * previously configured separator between each.
191   *
192   * @since 11.0
193   */
194  public final String join(Iterator<?> parts) {
195    return appendTo(new StringBuilder(), parts).toString();
196  }
197
198  /**
199   * Returns a string containing the string representation of each of {@code parts}, using the
200   * previously configured separator between each.
201   */
202  public final String join(Object[] parts) {
203    return join(Arrays.asList(parts));
204  }
205
206  /**
207   * Returns a string containing the string representation of each argument, using the previously
208   * configured separator between each.
209   */
210  public final String join(@Nullable Object first, @Nullable Object second, Object... rest) {
211    return join(iterable(first, second, rest));
212  }
213
214  /**
215   * Returns a joiner with the same behavior as this one, except automatically substituting {@code
216   * nullText} for any provided null elements.
217   */
218  public Joiner useForNull(final String nullText) {
219    checkNotNull(nullText);
220    return new Joiner(this) {
221      @Override
222      CharSequence toString(@Nullable Object part) {
223        return (part == null) ? nullText : Joiner.this.toString(part);
224      }
225
226      @Override
227      public Joiner useForNull(String nullText) {
228        throw new UnsupportedOperationException("already specified useForNull");
229      }
230
231      @Override
232      public Joiner skipNulls() {
233        throw new UnsupportedOperationException("already specified useForNull");
234      }
235    };
236  }
237
238  /**
239   * Returns a joiner with the same behavior as this joiner, except automatically skipping over any
240   * provided null elements.
241   */
242  public Joiner skipNulls() {
243    return new Joiner(this) {
244      @Override
245      public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
246        checkNotNull(appendable, "appendable");
247        checkNotNull(parts, "parts");
248        while (parts.hasNext()) {
249          Object part = parts.next();
250          if (part != null) {
251            appendable.append(Joiner.this.toString(part));
252            break;
253          }
254        }
255        while (parts.hasNext()) {
256          Object part = parts.next();
257          if (part != null) {
258            appendable.append(separator);
259            appendable.append(Joiner.this.toString(part));
260          }
261        }
262        return appendable;
263      }
264
265      @Override
266      public Joiner useForNull(String nullText) {
267        throw new UnsupportedOperationException("already specified skipNulls");
268      }
269
270      @Override
271      public MapJoiner withKeyValueSeparator(String kvs) {
272        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
273      }
274    };
275  }
276
277  /**
278   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
279   * this {@code Joiner} otherwise.
280   *
281   * @since 20.0
282   */
283  public MapJoiner withKeyValueSeparator(char keyValueSeparator) {
284    return withKeyValueSeparator(String.valueOf(keyValueSeparator));
285  }
286
287  /**
288   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
289   * this {@code Joiner} otherwise.
290   */
291  public MapJoiner withKeyValueSeparator(String keyValueSeparator) {
292    return new MapJoiner(this, keyValueSeparator);
293  }
294
295  /**
296   * An object that joins map entries in the same manner as {@code Joiner} joins iterables and
297   * arrays. Like {@code Joiner}, it is thread-safe and immutable.
298   *
299   * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code
300   * Multimap} entries in two distinct modes:
301   *
302   * <ul>
303   *   <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a
304   *       {@code MapJoiner} method that accepts entries as input, and receive output of the form
305   *       {@code key1=A&key1=B&key2=C}.
306   *   <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code
307   *       MapJoiner} method that accepts a map as input, and receive output of the form {@code
308   *       key1=[A, B]&key2=C}.
309   * </ul>
310   *
311   * @since 2.0
312   */
313  public static final class MapJoiner {
314    private final Joiner joiner;
315    private final String keyValueSeparator;
316
317    private MapJoiner(Joiner joiner, String keyValueSeparator) {
318      this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull
319      this.keyValueSeparator = checkNotNull(keyValueSeparator);
320    }
321
322    /**
323     * Appends the string representation of each entry of {@code map}, using the previously
324     * configured separator and key-value separator, to {@code appendable}.
325     */
326    @CanIgnoreReturnValue
327    public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {
328      return appendTo(appendable, map.entrySet());
329    }
330
331    /**
332     * Appends the string representation of each entry of {@code map}, using the previously
333     * configured separator and key-value separator, to {@code builder}. Identical to {@link
334     * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.
335     */
336    @CanIgnoreReturnValue
337    public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {
338      return appendTo(builder, map.entrySet());
339    }
340
341    /**
342     * Appends the string representation of each entry in {@code entries}, using the previously
343     * configured separator and key-value separator, to {@code appendable}.
344     *
345     * @since 10.0
346     */
347    @Beta
348    @CanIgnoreReturnValue
349    public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
350        throws IOException {
351      return appendTo(appendable, entries.iterator());
352    }
353
354    /**
355     * Appends the string representation of each entry in {@code entries}, using the previously
356     * configured separator and key-value separator, to {@code appendable}.
357     *
358     * @since 11.0
359     */
360    @Beta
361    @CanIgnoreReturnValue
362    public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
363        throws IOException {
364      checkNotNull(appendable);
365      if (parts.hasNext()) {
366        Entry<?, ?> entry = parts.next();
367        appendable.append(joiner.toString(entry.getKey()));
368        appendable.append(keyValueSeparator);
369        appendable.append(joiner.toString(entry.getValue()));
370        while (parts.hasNext()) {
371          appendable.append(joiner.separator);
372          Entry<?, ?> e = parts.next();
373          appendable.append(joiner.toString(e.getKey()));
374          appendable.append(keyValueSeparator);
375          appendable.append(joiner.toString(e.getValue()));
376        }
377      }
378      return appendable;
379    }
380
381    /**
382     * Appends the string representation of each entry in {@code entries}, using the previously
383     * configured separator and key-value separator, to {@code builder}. Identical to {@link
384     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
385     *
386     * @since 10.0
387     */
388    @Beta
389    @CanIgnoreReturnValue
390    public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
391      return appendTo(builder, entries.iterator());
392    }
393
394    /**
395     * Appends the string representation of each entry in {@code entries}, using the previously
396     * configured separator and key-value separator, to {@code builder}. Identical to {@link
397     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
398     *
399     * @since 11.0
400     */
401    @Beta
402    @CanIgnoreReturnValue
403    public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
404      try {
405        appendTo((Appendable) builder, entries);
406      } catch (IOException impossible) {
407        throw new AssertionError(impossible);
408      }
409      return builder;
410    }
411
412    /**
413     * Returns a string containing the string representation of each entry of {@code map}, using the
414     * previously configured separator and key-value separator.
415     */
416    public String join(Map<?, ?> map) {
417      return join(map.entrySet());
418    }
419
420    /**
421     * Returns a string containing the string representation of each entry in {@code entries}, using
422     * the previously configured separator and key-value separator.
423     *
424     * @since 10.0
425     */
426    @Beta
427    public String join(Iterable<? extends Entry<?, ?>> entries) {
428      return join(entries.iterator());
429    }
430
431    /**
432     * Returns a string containing the string representation of each entry in {@code entries}, using
433     * the previously configured separator and key-value separator.
434     *
435     * @since 11.0
436     */
437    @Beta
438    public String join(Iterator<? extends Entry<?, ?>> entries) {
439      return appendTo(new StringBuilder(), entries).toString();
440    }
441
442    /**
443     * Returns a map joiner with the same behavior as this one, except automatically substituting
444     * {@code nullText} for any provided null keys or values.
445     */
446    public MapJoiner useForNull(String nullText) {
447      return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);
448    }
449  }
450
451  CharSequence toString(Object part) {
452    checkNotNull(part); // checkNotNull for GWT (do not optimize).
453    return (part instanceof CharSequence) ? (CharSequence) part : part.toString();
454  }
455
456  private static Iterable<Object> iterable(
457      final Object first, final Object second, final Object[] rest) {
458    checkNotNull(rest);
459    return new AbstractList<Object>() {
460      @Override
461      public int size() {
462        return rest.length + 2;
463      }
464
465      @Override
466      public Object get(int index) {
467        switch (index) {
468          case 0:
469            return first;
470          case 1:
471            return second;
472          default:
473            return rest[index - 2];
474        }
475      }
476    };
477  }
478}