Top Description Inners Fields Constructors Methods
com.google.common.base

public final Class Splitter

extends Object
Class Inheritance
Annotations
@GwtCompatible
emulated:true
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull

Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed string, regular expression or CharMatcher instance. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixed length.

For example, this expression:

Splitter.on(',').split("foo,bar,qux")
... produces an Iterable containing "foo", "bar" and "qux", in that order.

By default, Splitter's behavior is simplistic and unassuming. The following expression:

Splitter.on(',').split(" foo,,,  bar ,")
... yields the substrings [" foo", "", "", " bar ", ""]. If this is not the desired behavior, use configuration methods to obtain a new splitter instance with modified behavior:
private static final Splitter MY_SPLITTER = Splitter.on(',')
    .trimResults()
    .omitEmptyStrings();

Now MY_SPLITTER.split("foo,,, bar ,") returns just ["foo", "bar"]. Note that the order in which these configuration methods are called is never significant.

Warning

Splitter instances are immutable. Invoking a configuration method has no effect on the receiving instance; you must store and use the new splitter instance it returns instead.

// Do NOT do this
Splitter splitter = Splitter.on('/');
splitter.trimResults(); // does nothing!
return splitter.split("wrong / wrong / wrong");

For separator-based splitters that do not use omitEmptyStrings, an input string containing n occurrences of the separator naturally yields an iterable of size n + 1. So if the separator does not occur anywhere in the input, a single substring is returned containing the entire input. Consequently, all splitters split the empty string to [""] (note: even fixed-length splitters).

Splitter instances are thread-safe immutable, and are therefore safe to store as static final constants.

The Joiner class provides the inverse operation to splitting, but note that a round-trip between the two should be assumed to be lossy.

See the Guava User Guide article on Splitter.

Authors
Julien Silland, Jesse Wilson, Kevin Bourrillion, Louis Wasserman
Since
1.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
Splitter.MapSplitter

An object that splits strings into maps as Splitter splits iterables and lists.

private abstract static class
private static interface

Field Summary

Modifier and TypeField and Description
private final int
private final boolean
private final Splitter.Strategy
private final CharMatcher

Constructor Summary

AccessConstructor and Description
private
private
Splitter(Splitter.Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit)

Method Summary

Modifier and TypeMethod and Description
public static Splitter

Returns:

a splitter, with default settings, that can split into fixed sized pieces
fixedLength
(final int
the desired length of pieces after splitting, a positive integer
length
)

Returns a splitter that divides strings into pieces of the given length.

public Splitter

Returns:

a splitter with the desired configuration
limit
(int
the maximum number of items returned
maxItems
)

Returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit.

public Splitter

Returns:

a splitter with the desired configuration
omitEmptyStrings
()

Returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results.

public static Splitter

Returns:

a splitter, with default settings, that recognizes that separator
on
(char
the character to recognize as a separator
separator
)

Returns a splitter that uses the given single-character separator.

public static Splitter

Returns:

a splitter, with default settings, that uses this matcher
on
(final CharMatcher
a CharMatcher that determines whether a character is a separator
separatorMatcher
)

Returns a splitter that considers any single character matched by the given CharMatcher to be a separator.

public static Splitter

Returns:

a splitter, with default settings, that recognizes that separator
on
(final String
the literal, nonempty string to recognize as a separator
separator
)

Returns a splitter that uses the given fixed string as a separator.

public static Splitter

Returns:

a splitter, with default settings, that uses this pattern
on
(Pattern
the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
separatorPattern
)

Returns a splitter that considers any subsequence matching pattern to be a separator.

public static Splitter

Returns:

a splitter, with default settings, that uses this pattern
onPattern
(String
the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
separatorPattern
)

Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator.

pack-priv static Splitter
onPatternInternal(final CommonPattern separatorPattern)

Internal utility; see on(Pattern) instead.

public Iterable<String>

Returns:

an iteration over the segments split from the parameter
split
(final CharSequence
the sequence of characters to split
sequence
)

Splits sequence into string components and makes them available through an Iterator, which may be lazily evaluated.

private Iterator<String>
public List<String>

Returns:

an immutable list of the segments split from the parameter
splitToList
(CharSequence
the sequence of characters to split
sequence
)

Splits sequence into string components and returns them as an immutable list.

public Stream<String>

Returns:

a stream over the segments split from the parameter
splitToStream
(CharSequence
the sequence of characters to split
sequence
)

Splits sequence into string components and makes them available through an Stream, which may be lazily evaluated.

public Splitter

Returns:

a splitter with the desired configuration
trimResults
()

Returns a splitter that behaves equivalently to this splitter, but automatically removes leading and trailing whitespace from each returned substring; equivalent to trimResults(CharMatcher.whitespace()).

public Splitter

Returns:

a splitter with the desired configuration
trimResults
(CharMatcher
a CharMatcher that determines whether a character should be removed from the beginning/end of a subsequence
trimmer
)

Returns a splitter that behaves equivalently to this splitter, but removes all leading or trailing characters matching the given CharMatcher from each returned substring.

public Splitter.MapSplitter
withKeyValueSeparator(String separator)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

public Splitter.MapSplitter
withKeyValueSeparator(char separator)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

public Splitter.MapSplitter
withKeyValueSeparator(Splitter keyValueSplitter)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified key-value splitter.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

limitback to summary
private final int limit
omitEmptyStringsback to summary
private final boolean omitEmptyStrings
strategyback to summary
private final Splitter.Strategy strategy
trimmerback to summary
private final CharMatcher trimmer

Constructor Detail

Splitterback to summary
private Splitter(Splitter.Strategy strategy)
Splitterback to summary
private Splitter(Splitter.Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit)

Method Detail

fixedLengthback to summary
public static Splitter fixedLength(final int length)

Returns a splitter that divides strings into pieces of the given length. For example, Splitter.fixedLength(2).split("abcde") returns an iterable containing ["ab", "cd", "e"]. The last piece can be smaller than length but will never be empty.

Note

if fixedLength is used in conjunction with limit, the final split piece may be longer than the specified fixed length. This is because the splitter will stop splitting when the limit is reached, and just return the final piece as-is.

Exception: for consistency with separator-based splitters, split("") does not yield an empty iterable, but an iterable containing "". This is the only case in which Iterables.size(split(input)) does not equal IntMath.divide(input.length(), length, CEILING). To avoid this behavior, use omitEmptyStrings.

Parameters
length:int

the desired length of pieces after splitting, a positive integer

Returns:Splitter

a splitter, with default settings, that can split into fixed sized pieces

Exceptions
IllegalArgumentException:
if length is zero or negative
limitback to summary
public Splitter limit(int maxItems)

Returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit. The limit defines the maximum number of items returned by the iterator, or the maximum size of the list returned by splitToList.

For example, Splitter.on(',').limit(3).split("a,b,c,d") returns an iterable containing ["a", "b", "c,d"]. When omitting empty strings, the omitted strings do not count. Hence, Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d") returns an iterable containing ["a", "b", "c,d"]. When trim is requested, all entries are trimmed, including the last. Hence Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ") results in ["a", "b", "c , d"].

Parameters
maxItems:int

the maximum number of items returned

Returns:Splitter

a splitter with the desired configuration

Since
9.0
omitEmptyStringsback to summary
public Splitter omitEmptyStrings()

Returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results. For example, Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,") returns an iterable containing only ["a", "b", "c"].

If either trimResults option is also specified when creating a splitter, that splitter always trims results first before checking for emptiness. So, for example, Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ") returns an empty iterable.

Note that it is ordinarily not possible for split(CharSequence) to return an empty iterable, but when using this option, it can (if the input sequence consists of nothing but separators).

Returns:Splitter

a splitter with the desired configuration

onback to summary
public static Splitter on(char separator)

Returns a splitter that uses the given single-character separator. For example, Splitter.on(',').split("foo,,bar") returns an iterable containing ["foo", "", "bar"].

Parameters
separator:char

the character to recognize as a separator

Returns:Splitter

a splitter, with default settings, that recognizes that separator

onback to summary
public static Splitter on(final CharMatcher separatorMatcher)

Returns a splitter that considers any single character matched by the given CharMatcher to be a separator. For example, Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux") returns an iterable containing ["foo", "", "bar", "quux"].

Parameters
separatorMatcher:CharMatcher

a CharMatcher that determines whether a character is a separator

Returns:Splitter

a splitter, with default settings, that uses this matcher

onback to summary
public static Splitter on(final String separator)

Returns a splitter that uses the given fixed string as a separator. For example, Splitter.on(", ").split("foo, bar,baz") returns an iterable containing ["foo", "bar,baz"].

Parameters
separator:String

the literal, nonempty string to recognize as a separator

Returns:Splitter

a splitter, with default settings, that recognizes that separator

onback to summary
public static Splitter on(Pattern separatorPattern)

Returns a splitter that considers any subsequence matching pattern to be a separator. For example, Splitter.on(Pattern.compile("\r?\n")).split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators.

Parameters
separatorPattern:Pattern

the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.

Returns:Splitter

a splitter, with default settings, that uses this pattern

Annotations
@GwtIncompatible
Exceptions
IllegalArgumentException:
if separatorPattern matches the empty string
onPatternback to summary
public static Splitter onPattern(String separatorPattern)

Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator. For example, Splitter.onPattern("\r?\n").split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent to Splitter.on(Pattern.compile(pattern)).

Parameters
separatorPattern:String

the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.

Returns:Splitter

a splitter, with default settings, that uses this pattern

Annotations
@GwtIncompatible
Exceptions
IllegalArgumentException:
if separatorPattern matches the empty string or is a malformed expression
onPatternInternalback to summary
pack-priv static Splitter onPatternInternal(final CommonPattern separatorPattern)

Internal utility; see on(Pattern) instead.

splitback to summary
public Iterable<String> split(final CharSequence sequence)

Splits sequence into string components and makes them available through an Iterator, which may be lazily evaluated. If you want an eagerly computed List, use splitToList(CharSequence). Java 8+ users may prefer splitToStream instead.

Parameters
sequence:CharSequence

the sequence of characters to split

Returns:Iterable<String>

an iteration over the segments split from the parameter

splittingIteratorback to summary
private Iterator<String> splittingIterator(CharSequence sequence)
splitToListback to summary
public List<String> splitToList(CharSequence sequence)

Splits sequence into string components and returns them as an immutable list. If you want an Iterable which may be lazily evaluated, use split(CharSequence).

Parameters
sequence:CharSequence

the sequence of characters to split

Returns:List<String>

an immutable list of the segments split from the parameter

Since
15.0
splitToStreamback to summary
public Stream<String> splitToStream(CharSequence sequence)

Splits sequence into string components and makes them available through an Stream, which may be lazily evaluated. If you want an eagerly computed List, use splitToList(CharSequence).

Parameters
sequence:CharSequence

the sequence of characters to split

Returns:Stream<String>

a stream over the segments split from the parameter

Since
28.2
trimResultsback to summary
public Splitter trimResults()

Returns a splitter that behaves equivalently to this splitter, but automatically removes leading and trailing whitespace from each returned substring; equivalent to trimResults(CharMatcher.whitespace()). For example, Splitter.on(',').trimResults().split(" a, b ,c ") returns an iterable containing ["a", "b", "c"].

Returns:Splitter

a splitter with the desired configuration

trimResultsback to summary
public Splitter trimResults(CharMatcher trimmer)

Returns a splitter that behaves equivalently to this splitter, but removes all leading or trailing characters matching the given CharMatcher from each returned substring. For example, Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__") returns an iterable containing ["a ", "b_ ", "c"].

Parameters
trimmer:CharMatcher

a CharMatcher that determines whether a character should be removed from the beginning/end of a subsequence

Returns:Splitter

a splitter with the desired configuration

withKeyValueSeparatorback to summary
public Splitter.MapSplitter withKeyValueSeparator(String separator)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

Since
10.0
withKeyValueSeparatorback to summary
public Splitter.MapSplitter withKeyValueSeparator(char separator)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.

Since
14.0
withKeyValueSeparatorback to summary
public Splitter.MapSplitter withKeyValueSeparator(Splitter keyValueSplitter)

Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified key-value splitter.

Note

Any configuration option configured on this splitter, such as trimResults, does not change the behavior of the keyValueSplitter.

Example:

String toSplit = " x -> y, z-> a ";
Splitter outerSplitter = Splitter.on(',').trimResults();
MapSplitter mapSplitter = outerSplitter.withKeyValueSeparator(Splitter.on("->"));
Map<String, String> result = mapSplitter.split(toSplit);
assertThat(result).isEqualTo(ImmutableMap.of("x ", " y", "z", " a"));
Since
10.0
com.google.common.base back to summary

public final Class Splitter.MapSplitter

extends Object
Class Inheritance

An object that splits strings into maps as Splitter splits iterables and lists. Like Splitter, it is thread-safe and immutable. The common way to build instances is by providing an additional key-value separator to Splitter.
Since
10.0

Field Summary

Modifier and TypeField and Description
private final Splitter
private static final String
private final Splitter

Constructor Summary

AccessConstructor and Description
private
MapSplitter(Splitter outerSplitter, Splitter entrySplitter)

Method Summary

Modifier and TypeMethod and Description
public Map<String, String>
split(CharSequence sequence)

Splits sequence into substrings, splits each substring into an entry, and returns an unmodifiable map with each of the entries.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

entrySplitterback to summary
private final Splitter entrySplitter
INVALID_ENTRY_MESSAGEback to summary
private static final String INVALID_ENTRY_MESSAGE
outerSplitterback to summary
private final Splitter outerSplitter

Constructor Detail

MapSplitterback to summary
private MapSplitter(Splitter outerSplitter, Splitter entrySplitter)

Method Detail

splitback to summary
public Map<String, String> split(CharSequence sequence)

Splits sequence into substrings, splits each substring into an entry, and returns an unmodifiable map with each of the entries. For example, Splitter.on(';').trimResults().withKeyValueSeparator("=>").split("a=>b ; c=>b") will return a mapping from "a" to "b" and "c" to "b".

The returned map preserves the order of the entries from sequence.

Exceptions
IllegalArgumentException:
if the specified sequence does not split into valid map entries, or if there are duplicate keys
com.google.common.base back to summary

private abstract Class Splitter.SplittingIterator

extends AbstractIterator<String>
Class Inheritance

Field Summary

Modifier and TypeField and Description
pack-priv int
pack-priv int
pack-priv final boolean
pack-priv final CharSequence
pack-priv final CharMatcher

Constructor Summary

AccessConstructor and Description
protected

Method Summary

Modifier and TypeMethod and Description
protected String
pack-priv abstract int
separatorEnd(int separatorPosition)

Returns the first index in toSplit after separatorPosition that does not contain a separator.

pack-priv abstract int
separatorStart(int start)

Returns the first index in toSplit at or after start that contains the separator.

Inherited from com.google.common.base.AbstractIterator:
endOfDatahasNextnextremove

Field Detail

limitback to summary
pack-priv int limit
offsetback to summary
pack-priv int offset
omitEmptyStringsback to summary
pack-priv final boolean omitEmptyStrings
toSplitback to summary
pack-priv final CharSequence toSplit
trimmerback to summary
pack-priv final CharMatcher trimmer

Constructor Detail

SplittingIteratorback to summary
protected SplittingIterator(Splitter splitter, CharSequence toSplit)

Method Detail

computeNextback to summary
protected String computeNext()

Implements abstract com.google.common.base.AbstractIterator.computeNext.

Annotations
@CheckForNull
@Override
separatorEndback to summary
pack-priv abstract int separatorEnd(int separatorPosition)

Returns the first index in toSplit after separatorPosition that does not contain a separator. This method is only invoked after a call to separatorStart.

separatorStartback to summary
pack-priv abstract int separatorStart(int start)

Returns the first index in toSplit at or after start that contains the separator.

com.google.common.base back to summary

private Interface Splitter.Strategy


Method Summary

Modifier and TypeMethod and Description
public Iterator<String>
iterator(Splitter splitter, CharSequence toSplit)

Method Detail

iteratorback to summary
public Iterator<String> iterator(Splitter splitter, CharSequence toSplit)