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