Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.base;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.Map;
 
 import  javax.annotation.CheckReturnValue;
 import  javax.annotation.Nullable;

An object which joins pieces of text (specified as an array, Iterable, varargs or even a Map) with a separator. It either appends the results to an Appendable or returns them as a String. Example:
   Joiner joiner = Joiner.on("; ").skipNulls();
    . . .
   return joiner.join("Harry", null, "Ron", "Hermione");
This returns the string "Harry; Ron; Hermione". Note that all input elements are converted to strings using Object.toString() before being appended.

If neither skipNulls() nor useForNull(String) is specified, the joining methods will throw NullPointerException if any given element is null.

Warning: joiner instances are always immutable; a configuration method such as useForNull has no effect on the instance it is invoked on! You must store and use the new joiner instance returned by the method. This makes joiners thread-safe, and safe to store as static final constants.

   // Bad! Do not do this!
   Joiner joiner = Joiner.on(',');
   joiner.skipNulls(); // does nothing!
   return joiner.join("wrong", null, "wrong");

See the Guava User Guide article on Joiner.

Author(s):
Kevin Bourrillion
Since:
2.0 (imported from Google Collections Library)
 
 public class Joiner {
  
Returns a joiner which automatically places separator between consecutive elements.
 
   public static Joiner on(String separator) {
     return new Joiner(separator);
   }

  
Returns a joiner which automatically places separator between consecutive elements.
 
   public static Joiner on(char separator) {
     return new Joiner(String.valueOf(separator));
   }
 
   private final String separator;
 
   private Joiner(String separator) {
     this. = checkNotNull(separator);
   }
 
   private Joiner(Joiner prototype) {
     this. = prototype.separator;
   }

  
Deprecated.

Deprecated:
use appendTo(Appendable, Iterator) by casting parts to Iterator<?>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
 
   @Beta
  public
  final <A extends Appendable, I extends Object & Iterable<?> & Iterator<?>> A
      appendTo(A appendable, I partsthrows IOException {
    return appendTo(appendable, (Iterator<?>) parts);
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to appendable.
  public <A extends Appendable> A appendTo(A appendableIterable<?> partsthrows IOException {
    return appendTo(appendableparts.iterator());
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to appendable.

Since:
11.0
  public <A extends Appendable> A appendTo(A appendableIterator<?> partsthrows IOException {
    checkNotNull(appendable);
    if (parts.hasNext()) {
      appendable.append(toString(parts.next()));
      while (parts.hasNext()) {
        appendable.append();
        appendable.append(toString(parts.next()));
      }
    }
    return appendable;
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to appendable.
  public final <A extends Appendable> A appendTo(A appendableObject[] partsthrows IOException {
    return appendTo(appendable, Arrays.asList(parts));
  }

  
Appends to appendable the string representation of each of the remaining arguments.
  public final <A extends Appendable> A appendTo(
      A appendable, @Nullable Object first, @Nullable Object secondObject... rest)
          throws IOException {
    return appendTo(appendableiterable(firstsecondrest));
  }

  
Deprecated.

Deprecated:
use appendTo(StringBuilder, Iterator) by casting parts to Iterator<?>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
  @Beta
  public
  final <I extends Object & Iterable<?> & Iterator<?>> StringBuilder
      appendTo(StringBuilder builder, I parts) {
    return appendTo(builder, (Iterator<?>) parts);
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to builder. Identical to appendTo(Appendable, Iterable), except that it does not throw IOException.
  public final StringBuilder appendTo(StringBuilder builderIterable<?> parts) {
    return appendTo(builderparts.iterator());
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to builder. Identical to appendTo(Appendable, Iterable), except that it does not throw IOException.

Since:
11.0
  public final StringBuilder appendTo(StringBuilder builderIterator<?> parts) {
    try {
      appendTo((Appendablebuilderparts);
    } catch (IOException impossible) {
      throw new AssertionError(impossible);
    }
    return builder;
  }

  
Appends the string representation of each of parts, using the previously configured separator between each, to builder. Identical to appendTo(Appendable, Iterable), except that it does not throw IOException.
  public final StringBuilder appendTo(StringBuilder builderObject[] parts) {
    return appendTo(builder, Arrays.asList(parts));
  }

  
Appends to builder the string representation of each of the remaining arguments. Identical to appendTo(Appendable, Object, Object, Object...), except that it does not throw IOException.
  public final StringBuilder appendTo(
      StringBuilder builder, @Nullable Object first, @Nullable Object secondObject... rest) {
    return appendTo(builderiterable(firstsecondrest));
  }

  
Deprecated.

Deprecated:
use join(Iterator) by casting parts to Iterator<?>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
  @Beta
  public
  final <I extends Object & Iterable<?> & Iterator<?>> String join(I parts) {
    return join((Iterator<?>) parts);
  }

  
Returns a string containing the string representation of each of parts, using the previously configured separator between each.
  public final String join(Iterable<?> parts) {
    return join(parts.iterator());
  }

  
Returns a string containing the string representation of each of parts, using the previously configured separator between each.

Since:
11.0
  public final String join(Iterator<?> parts) {
    return appendTo(new StringBuilder(), parts).toString();
  }

  
Returns a string containing the string representation of each of parts, using the previously configured separator between each.
  public final String join(Object[] parts) {
    return join(Arrays.asList(parts));
  }

  
Returns a string containing the string representation of each argument, using the previously configured separator between each.
  public final String join(@Nullable Object first, @Nullable Object secondObject... rest) {
    return join(iterable(firstsecondrest));
  }

  
Returns a joiner with the same behavior as this one, except automatically substituting nullText for any provided null elements.
  @CheckReturnValue
  public Joiner useForNull(final String nullText) {
    checkNotNull(nullText);
    return new Joiner(this) {
      @Override CharSequence toString(Object part) {
        return (part == null) ? nullText : Joiner.this.toString(part);
      }
      @Override public Joiner useForNull(String nullText) {
        checkNotNull(nullText); // weird: just to satisfy NullPointerTester.
        throw new UnsupportedOperationException("already specified useForNull");
      }
      @Override public Joiner skipNulls() {
        throw new UnsupportedOperationException("already specified useForNull");
      }
    };
  }

  
Returns a joiner with the same behavior as this joiner, except automatically skipping over any provided null elements.
  @CheckReturnValue
  public Joiner skipNulls() {
    return new Joiner(this) {
      @Override public <A extends Appendable> A appendTo(A appendableIterator<?> parts)
          throws IOException {
        checkNotNull(appendable"appendable");
        checkNotNull(parts"parts");
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append(Joiner.this.toString(part));
            break;
          }
        }
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append();
            appendable.append(Joiner.this.toString(part));
          }
        }
        return appendable;
      }
      @Override public Joiner useForNull(String nullText) {
        checkNotNull(nullText); // weird: just to satisfy NullPointerTester.
        throw new UnsupportedOperationException("already specified skipNulls");
      }
      @Override public MapJoiner withKeyValueSeparator(String kvs) {
        checkNotNull(kvs); // weird: just to satisfy NullPointerTester.
        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
      }
    };
  }

  
Returns a MapJoiner using the given key-value separator, and the same configuration as this Joiner otherwise.
  @CheckReturnValue
  public MapJoiner withKeyValueSeparator(String keyValueSeparator) {
    return new MapJoiner(thiskeyValueSeparator);
  }

  
An object that joins map entries in the same manner as Joiner joins iterables and arrays. Like Joiner, it is thread-safe and immutable.

In addition to operating on Map instances, MapJoiner can operate on Multimap entries in two distinct modes:

  • To output a separate entry for each key-value pair, pass multimap.entries() to a MapJoiner method that accepts entries as input, and receive output of the form key1=A&key1=B&key2=C.
  • To output a single entry for each key, pass multimap.asMap() to a MapJoiner method that accepts a map as input, and receive output of the form key1=[A, B]&key2=C.

Since:
2.0 (imported from Google Collections Library)
  public final static class MapJoiner {
    private final Joiner joiner;
    private final String keyValueSeparator;
    private MapJoiner(Joiner joinerString keyValueSeparator) {
      this. = joiner// only "this" is ever passed, so don't checkNotNull
      this. = checkNotNull(keyValueSeparator);
    }

    
Appends the string representation of each entry of map, using the previously configured separator and key-value separator, to appendable.
    public <A extends Appendable> A appendTo(A appendableMap<?, ?> mapthrows IOException {
      return appendTo(appendablemap.entrySet());
    }

    
Appends the string representation of each entry of map, using the previously configured separator and key-value separator, to builder. Identical to appendTo(Appendable, Map), except that it does not throw IOException.
    public StringBuilder appendTo(StringBuilder builderMap<?, ?> map) {
      return appendTo(buildermap.entrySet());
    }

    
Returns a string containing the string representation of each entry of map, using the previously configured separator and key-value separator.
    public String join(Map<?, ?> map) {
      return join(map.entrySet());
    }

    
Deprecated.

Deprecated:
use appendTo(Appendable, Iterator) by casting entries to Iterator<? extends Entry<?, ?>>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
    @Beta
    @Deprecated
    public
    <A extends Appendable,
        I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
        A appendTo(A appendable, I entriesthrows IOException {
      Iterator<? extends Entry<?, ?>> iterator = entries;
      return appendTo(appendableiterator);
    }

    
Appends the string representation of each entry in entries, using the previously configured separator and key-value separator, to appendable.

Since:
10.0
    @Beta
    public <A extends Appendable> A appendTo(A appendableIterable<? extends Entry<?, ?>> entries)
        throws IOException {
      return appendTo(appendableentries.iterator());
    }

    
Appends the string representation of each entry in entries, using the previously configured separator and key-value separator, to appendable.

Since:
11.0
    @Beta
    public <A extends Appendable> A appendTo(A appendableIterator<? extends Entry<?, ?>> parts)
        throws IOException {
      checkNotNull(appendable);
      if (parts.hasNext()) {
        Entry<?, ?> entry = parts.next();
        appendable.append(.toString(entry.getKey()));
        appendable.append();
        appendable.append(.toString(entry.getValue()));
        while (parts.hasNext()) {
          appendable.append(.);
          Entry<?, ?> e = parts.next();
          appendable.append(.toString(e.getKey()));
          appendable.append();
          appendable.append(.toString(e.getValue()));
        }
      }
      return appendable;
    }

    
Deprecated.

Deprecated:
use appendTo(StringBuilder, Iterator) by casting entries to Iterator<? extends Entry<?, ?>>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
    @Beta
    @Deprecated
    public
    <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
        StringBuilder appendTo(StringBuilder builder, I entriesthrows IOException {
      Iterator<? extends Entry<?, ?>> iterator = entries;
      return appendTo(builderiterator);
    }

    
Appends the string representation of each entry in entries, using the previously configured separator and key-value separator, to builder. Identical to appendTo(Appendable, Iterable), except that it does not throw IOException.

Since:
10.0
    @Beta
    public StringBuilder appendTo(StringBuilder builderIterable<? extends Entry<?, ?>> entries) {
      return appendTo(builderentries.iterator());
    }

    
Appends the string representation of each entry in entries, using the previously configured separator and key-value separator, to builder. Identical to appendTo(Appendable, Iterable), except that it does not throw IOException.

Since:
11.0
    @Beta
    public StringBuilder appendTo(StringBuilder builderIterator<? extends Entry<?, ?>> entries) {
      try {
        appendTo((Appendablebuilderentries);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
      return builder;
    }

    
Deprecated.

Deprecated:
use join(Iterator) by casting entries to Iterator<? extends Entry<?, ?>>, or better yet, by implementing only Iterator and not Iterable. This method is scheduled for deletion in June 2013.
Since:
11.0
    @Beta
    @Deprecated
    public
    <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
        String join(I entriesthrows IOException {
      Iterator<? extends Entry<?, ?>> iterator = entries;
      return join(iterator);
    }

    
Returns a string containing the string representation of each entry in entries, using the previously configured separator and key-value separator.

Since:
10.0
    @Beta
    public String join(Iterable<? extends Entry<?, ?>> entries) {
      return join(entries.iterator());
    }

    
Returns a string containing the string representation of each entry in entries, using the previously configured separator and key-value separator.

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

    
Returns a map joiner with the same behavior as this one, except automatically substituting nullText for any provided null keys or values.
    @CheckReturnValue
    public MapJoiner useForNull(String nullText) {
      return new MapJoiner(.useForNull(nullText), );
    }
  }
    checkNotNull(part);  // checkNotNull for GWT (do not optimize).
    return (part instanceof CharSequence) ? (CharSequencepart : part.toString();
  }
  private static Iterable<Objectiterable(
      final Object firstfinal Object secondfinal Object[] rest) {
    checkNotNull(rest);
    return new AbstractList<Object>() {
      @Override public int size() {
        return rest.length + 2;
      }
      @Override public Object get(int index) {
        switch (index) {
          case 0:
            return first;
          case 1:
            return second;
          default:
            return rest[index - 2];
        }
      }
    };
  }
New to GrepCode? Check out our FAQ X