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; 018import static java.util.Objects.requireNonNull; 019 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.List; 027import java.util.Map; 028import java.util.Map.Entry; 029import javax.annotation.CheckForNull; 030import org.checkerframework.checker.nullness.qual.Nullable; 031 032/** 033 * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a 034 * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns 035 * them as a {@link String}. Example: 036 * 037 * <pre>{@code 038 * Joiner joiner = Joiner.on("; ").skipNulls(); 039 * . . . 040 * return joiner.join("Harry", null, "Ron", "Hermione"); 041 * }</pre> 042 * 043 * <p>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. 053 * 054 * <pre>{@code 055 * // Bad! Do not do this! 056 * Joiner joiner = Joiner.on(','); 057 * joiner.skipNulls(); // does nothing! 058 * return joiner.join("wrong", null, "wrong"); 059 * }</pre> 060 * 061 * <p>See the Guava User Guide article on <a 062 * href="https://github.com/google/guava/wiki/StringsExplained#joiner">{@code Joiner}</a>. 063 * 064 * @author Kevin Bourrillion 065 * @since 2.0 066 */ 067@GwtCompatible 068public class Joiner { 069 /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ 070 public static Joiner on(String separator) { 071 return new Joiner(separator); 072 } 073 074 /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ 075 public static Joiner on(char separator) { 076 return new Joiner(String.valueOf(separator)); 077 } 078 079 private final String separator; 080 081 private Joiner(String separator) { 082 this.separator = checkNotNull(separator); 083 } 084 085 private Joiner(Joiner prototype) { 086 this.separator = prototype.separator; 087 } 088 089 /** 090 * Appends the string representation of each of {@code parts}, using the previously configured 091 * separator between each, to {@code appendable}. 092 */ 093 @CanIgnoreReturnValue 094 public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { 095 return appendTo(appendable, parts.iterator()); 096 } 097 098 /** 099 * Appends the string representation of each of {@code parts}, using the previously configured 100 * separator between each, to {@code appendable}. 101 * 102 * @since 11.0 103 */ 104 @CanIgnoreReturnValue 105 public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { 106 checkNotNull(appendable); 107 if (parts.hasNext()) { 108 appendable.append(toString(parts.next())); 109 while (parts.hasNext()) { 110 appendable.append(separator); 111 appendable.append(toString(parts.next())); 112 } 113 } 114 return appendable; 115 } 116 117 /** 118 * Appends the string representation of each of {@code parts}, using the previously configured 119 * separator between each, to {@code appendable}. 120 */ 121 @CanIgnoreReturnValue 122 public final <A extends Appendable> A appendTo(A appendable, @Nullable Object[] parts) 123 throws IOException { 124 @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker 125 List<?> partsList = Arrays.<@Nullable Object>asList(parts); 126 return appendTo(appendable, partsList); 127 } 128 129 /** Appends to {@code appendable} the string representation of each of the remaining arguments. */ 130 @CanIgnoreReturnValue 131 public final <A extends Appendable> A appendTo( 132 A appendable, 133 @CheckForNull Object first, 134 @CheckForNull Object second, 135 @Nullable Object... rest) 136 throws IOException { 137 return appendTo(appendable, iterable(first, second, rest)); 138 } 139 140 /** 141 * Appends the string representation of each of {@code parts}, using the previously configured 142 * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, 143 * Iterable)}, except that it does not throw {@link IOException}. 144 */ 145 @CanIgnoreReturnValue 146 public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) { 147 return appendTo(builder, parts.iterator()); 148 } 149 150 /** 151 * Appends the string representation of each of {@code parts}, using the previously configured 152 * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, 153 * Iterable)}, except that it does not throw {@link IOException}. 154 * 155 * @since 11.0 156 */ 157 @CanIgnoreReturnValue 158 public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) { 159 try { 160 appendTo((Appendable) builder, parts); 161 } catch (IOException impossible) { 162 throw new AssertionError(impossible); 163 } 164 return builder; 165 } 166 167 /** 168 * Appends the string representation of each of {@code parts}, using the previously configured 169 * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, 170 * Iterable)}, except that it does not throw {@link IOException}. 171 */ 172 @CanIgnoreReturnValue 173 public final StringBuilder appendTo(StringBuilder builder, @Nullable Object[] parts) { 174 @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker 175 List<?> partsList = Arrays.<@Nullable Object>asList(parts); 176 return appendTo(builder, partsList); 177 } 178 179 /** 180 * Appends to {@code builder} the string representation of each of the remaining arguments. 181 * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not 182 * throw {@link IOException}. 183 */ 184 @CanIgnoreReturnValue 185 public final StringBuilder appendTo( 186 StringBuilder builder, 187 @CheckForNull Object first, 188 @CheckForNull Object second, 189 @Nullable Object... rest) { 190 return appendTo(builder, iterable(first, second, rest)); 191 } 192 193 /** 194 * Returns a string containing the string representation of each of {@code parts}, using the 195 * previously configured separator between each. 196 */ 197 public String join(Iterable<?> parts) { 198 /* 199 * If we can quickly determine how many elements there are likely to be, then we can use the 200 * fastest possible implementation, which delegates to the array overload of String.join. 201 * 202 * In theory, we can quickly determine the size of any Collection. However, thanks to 203 * regrettable implementations like our own Sets.filter, Collection.size() is sometimes a 204 * linear-time operation, and it can even have side effects. Thus, we limit the special case to 205 * List, which is _even more likely_ to have size() implemented to be fast and side-effect-free. 206 * 207 * We could consider recognizing specific other collections as safe (like ImmutableCollection, 208 * except ContiguousSet!) or as not worth this optimization (CopyOnWriteArrayList?). 209 */ 210 if (parts instanceof List) { 211 int size = ((List<?>) parts).size(); 212 if (size == 0) { 213 return ""; 214 } 215 CharSequence[] toJoin = new CharSequence[size]; 216 int i = 0; 217 for (Object part : parts) { 218 if (i == toJoin.length) { 219 /* 220 * We first initialized toJoin to the size of the input collection. However, that size can 221 * go out of date (for a collection like CopyOnWriteArrayList, which may have been safely 222 * modified concurrently), or it might have been only an estimate to begin with (for a 223 * collection like ConcurrentHashMap, which sums up several counters that may not be in 224 * sync with one another). We accommodate that by resizing as necessary. 225 */ 226 toJoin = Arrays.copyOf(toJoin, expandedCapacity(toJoin.length, toJoin.length + 1)); 227 } 228 toJoin[i++] = toString(part); 229 } 230 // We might not have seen the expected number of elements, as discussed above. 231 if (i != toJoin.length) { 232 toJoin = Arrays.copyOf(toJoin, i); 233 } 234 // What we care about is Android, under which this method is always desugared: 235 // https://r8.googlesource.com/r8/+/05ba76883518bff06496d6d7df5f06b94a88fb00/src/main/java/com/android/tools/r8/ir/desugar/BackportedMethodRewriter.java#831 236 @SuppressWarnings("Java7ApiChecker") 237 String result = String.join(separator, toJoin); 238 return result; 239 } 240 return join(parts.iterator()); 241 } 242 243 /* 244 * TODO: b/381289911 - Make the Iterator overload use StringJoiner (including Android or not)—or 245 * some other optimization, given that StringJoiner can over-allocate: 246 * https://bugs.openjdk.org/browse/JDK-8305774 247 */ 248 249 // TODO: b/381289911 - Optimize MapJoiner similarly to Joiner (including Android or not). 250 251 /** 252 * Returns a string containing the string representation of each of {@code parts}, using the 253 * previously configured separator between each. 254 * 255 * @since 11.0 256 */ 257 public final String join(Iterator<?> parts) { 258 return appendTo(new StringBuilder(), parts).toString(); 259 } 260 261 /** 262 * Returns a string containing the string representation of each of {@code parts}, using the 263 * previously configured separator between each. 264 */ 265 public final String join(@Nullable Object[] parts) { 266 @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker 267 List<?> partsList = Arrays.<@Nullable Object>asList(parts); 268 return join(partsList); 269 } 270 271 /** 272 * Returns a string containing the string representation of each argument, using the previously 273 * configured separator between each. 274 */ 275 public final String join( 276 @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) { 277 return join(iterable(first, second, rest)); 278 } 279 280 /** 281 * Returns a joiner with the same behavior as this one, except automatically substituting {@code 282 * nullText} for any provided null elements. 283 */ 284 public Joiner useForNull(String nullText) { 285 checkNotNull(nullText); 286 return new Joiner(this) { 287 @Override 288 CharSequence toString(@CheckForNull Object part) { 289 return (part == null) ? nullText : Joiner.this.toString(part); 290 } 291 292 @Override 293 public Joiner useForNull(String nullText) { 294 throw new UnsupportedOperationException("already specified useForNull"); 295 } 296 297 @Override 298 public Joiner skipNulls() { 299 throw new UnsupportedOperationException("already specified useForNull"); 300 } 301 }; 302 } 303 304 /** 305 * Returns a joiner with the same behavior as this joiner, except automatically skipping over any 306 * provided null elements. 307 */ 308 public Joiner skipNulls() { 309 return new Joiner(this) { 310 @Override 311 @SuppressWarnings("JoinIterableIterator") // suggests infinite recursion 312 public String join(Iterable<? extends @Nullable Object> parts) { 313 return join(parts.iterator()); 314 } 315 316 @Override 317 public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { 318 checkNotNull(appendable, "appendable"); 319 checkNotNull(parts, "parts"); 320 while (parts.hasNext()) { 321 Object part = parts.next(); 322 if (part != null) { 323 appendable.append(Joiner.this.toString(part)); 324 break; 325 } 326 } 327 while (parts.hasNext()) { 328 Object part = parts.next(); 329 if (part != null) { 330 appendable.append(separator); 331 appendable.append(Joiner.this.toString(part)); 332 } 333 } 334 return appendable; 335 } 336 337 @Override 338 public Joiner useForNull(String nullText) { 339 throw new UnsupportedOperationException("already specified skipNulls"); 340 } 341 342 @Override 343 public MapJoiner withKeyValueSeparator(String kvs) { 344 throw new UnsupportedOperationException("can't use .skipNulls() with maps"); 345 } 346 }; 347 } 348 349 /** 350 * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as 351 * this {@code Joiner} otherwise. 352 * 353 * @since 20.0 354 */ 355 public MapJoiner withKeyValueSeparator(char keyValueSeparator) { 356 return withKeyValueSeparator(String.valueOf(keyValueSeparator)); 357 } 358 359 /** 360 * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as 361 * this {@code Joiner} otherwise. 362 */ 363 public MapJoiner withKeyValueSeparator(String keyValueSeparator) { 364 return new MapJoiner(this, keyValueSeparator); 365 } 366 367 /** 368 * An object that joins map entries in the same manner as {@code Joiner} joins iterables and 369 * arrays. Like {@code Joiner}, it is thread-safe and immutable. 370 * 371 * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code 372 * Multimap} entries in two distinct modes: 373 * 374 * <ul> 375 * <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a 376 * {@code MapJoiner} method that accepts entries as input, and receive output of the form 377 * {@code key1=A&key1=B&key2=C}. 378 * <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code 379 * MapJoiner} method that accepts a map as input, and receive output of the form {@code 380 * key1=[A, B]&key2=C}. 381 * </ul> 382 * 383 * @since 2.0 384 */ 385 public static final class MapJoiner { 386 private final Joiner joiner; 387 private final String keyValueSeparator; 388 389 private MapJoiner(Joiner joiner, String keyValueSeparator) { 390 this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull 391 this.keyValueSeparator = checkNotNull(keyValueSeparator); 392 } 393 394 /** 395 * Appends the string representation of each entry of {@code map}, using the previously 396 * configured separator and key-value separator, to {@code appendable}. 397 */ 398 @CanIgnoreReturnValue 399 public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException { 400 return appendTo(appendable, map.entrySet()); 401 } 402 403 /** 404 * Appends the string representation of each entry of {@code map}, using the previously 405 * configured separator and key-value separator, to {@code builder}. Identical to {@link 406 * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}. 407 */ 408 @CanIgnoreReturnValue 409 public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) { 410 return appendTo(builder, map.entrySet()); 411 } 412 413 /** 414 * Appends the string representation of each entry in {@code entries}, using the previously 415 * configured separator and key-value separator, to {@code appendable}. 416 * 417 * @since 10.0 418 */ 419 @CanIgnoreReturnValue 420 public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries) 421 throws IOException { 422 return appendTo(appendable, entries.iterator()); 423 } 424 425 /** 426 * Appends the string representation of each entry in {@code entries}, using the previously 427 * configured separator and key-value separator, to {@code appendable}. 428 * 429 * @since 11.0 430 */ 431 @CanIgnoreReturnValue 432 public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts) 433 throws IOException { 434 checkNotNull(appendable); 435 if (parts.hasNext()) { 436 Entry<?, ?> entry = parts.next(); 437 appendable.append(joiner.toString(entry.getKey())); 438 appendable.append(keyValueSeparator); 439 appendable.append(joiner.toString(entry.getValue())); 440 while (parts.hasNext()) { 441 appendable.append(joiner.separator); 442 Entry<?, ?> e = parts.next(); 443 appendable.append(joiner.toString(e.getKey())); 444 appendable.append(keyValueSeparator); 445 appendable.append(joiner.toString(e.getValue())); 446 } 447 } 448 return appendable; 449 } 450 451 /** 452 * Appends the string representation of each entry in {@code entries}, using the previously 453 * configured separator and key-value separator, to {@code builder}. Identical to {@link 454 * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. 455 * 456 * @since 10.0 457 */ 458 @CanIgnoreReturnValue 459 public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) { 460 return appendTo(builder, entries.iterator()); 461 } 462 463 /** 464 * Appends the string representation of each entry in {@code entries}, using the previously 465 * configured separator and key-value separator, to {@code builder}. Identical to {@link 466 * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. 467 * 468 * @since 11.0 469 */ 470 @CanIgnoreReturnValue 471 public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) { 472 try { 473 appendTo((Appendable) builder, entries); 474 } catch (IOException impossible) { 475 throw new AssertionError(impossible); 476 } 477 return builder; 478 } 479 480 /** 481 * Returns a string containing the string representation of each entry of {@code map}, using the 482 * previously configured separator and key-value separator. 483 */ 484 public String join(Map<?, ?> map) { 485 return join(map.entrySet()); 486 } 487 488 /** 489 * Returns a string containing the string representation of each entry in {@code entries}, using 490 * the previously configured separator and key-value separator. 491 * 492 * @since 10.0 493 */ 494 public String join(Iterable<? extends Entry<?, ?>> entries) { 495 return join(entries.iterator()); 496 } 497 498 /** 499 * Returns a string containing the string representation of each entry in {@code entries}, using 500 * the previously configured separator and key-value separator. 501 * 502 * @since 11.0 503 */ 504 public String join(Iterator<? extends Entry<?, ?>> entries) { 505 return appendTo(new StringBuilder(), entries).toString(); 506 } 507 508 /** 509 * Returns a map joiner with the same behavior as this one, except automatically substituting 510 * {@code nullText} for any provided null keys or values. 511 */ 512 public MapJoiner useForNull(String nullText) { 513 return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator); 514 } 515 } 516 517 // TODO(cpovirk): Rename to "toCharSequence." 518 CharSequence toString(@CheckForNull Object part) { 519 /* 520 * requireNonNull is not safe: Joiner.on(...).join(somethingThatContainsNull) will indeed throw. 521 * However, Joiner.on(...).useForNull(...).join(somethingThatContainsNull) *is* safe -- because 522 * it returns a subclass of Joiner that overrides this method to tolerate null inputs. 523 * 524 * Unfortunately, we don't distinguish between these two cases in our public API: Joiner.on(...) 525 * and Joiner.on(...).useForNull(...) both declare the same return type: plain Joiner. To ensure 526 * that users *can* pass null arguments to Joiner, we annotate it as if it always tolerates null 527 * inputs, rather than as if it never tolerates them. 528 * 529 * We rely on checkers to implement special cases to catch dangerous calls to join(), etc. based 530 * on what they know about the particular Joiner instances the calls are performed on. 531 * 532 * (In addition to useForNull, we also offer skipNulls. It, too, tolerates null inputs, but its 533 * tolerance is implemented differently: Its implementation avoids calling this toString(Object) 534 * method in the first place.) 535 */ 536 requireNonNull(part); 537 return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); 538 } 539 540 private static Iterable<@Nullable Object> iterable( 541 @CheckForNull Object first, @CheckForNull Object second, @Nullable Object[] rest) { 542 checkNotNull(rest); 543 return new AbstractList<@Nullable Object>() { 544 @Override 545 public int size() { 546 return rest.length + 2; 547 } 548 549 @Override 550 @CheckForNull 551 public Object get(int index) { 552 switch (index) { 553 case 0: 554 return first; 555 case 1: 556 return second; 557 default: 558 return rest[index - 2]; 559 } 560 } 561 }; 562 } 563 564 // cloned from ImmutableCollection 565 private static int expandedCapacity(int oldCapacity, int minCapacity) { 566 if (minCapacity < 0) { 567 throw new IllegalArgumentException("cannot store more than Integer.MAX_VALUE elements"); 568 } else if (minCapacity <= oldCapacity) { 569 return oldCapacity; 570 } 571 // careful of overflow! 572 int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; 573 if (newCapacity < minCapacity) { 574 newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; 575 } 576 if (newCapacity < 0) { 577 newCapacity = Integer.MAX_VALUE; 578 // guaranteed to be >= newCapacity 579 } 580 return newCapacity; 581 } 582}