前言
我们上篇文章讲述了Joiner相关API使用,其中提到了Splitter,它与Joiner操作相反,它是根据给定的分隔符,把一个字符串分隔成若个子字符串,那么本篇我们来看看Splitter都有哪些操作的方式。
Splitter
它与Joiner操作相反,它是根据给定的分隔符,把一个字符串分隔成若个子字符串,我们可以在com.google.common.base下找到它,如下:
package com.google.common.base;
import ....;
/**
* Extracts non-overlapping substrings from an input string, typically by
* recognizing appearances of a <i>separator</i> sequence. This separator can be
* specified as a single {@linkplain #on(char) character}, fixed {@linkplain
* #on(String) string}, {@linkplain #onPattern regular expression} or {@link
* #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at
* all, a splitter can extract adjacent substrings of a given {@linkplain
* #fixedLength fixed length}.
*
* <p>For example, this expression: <pre> {@code
*
* Splitter.on(',').split("foo,bar,qux")}</pre>
*
* ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and
* {@code "qux"}, in that order.
*
* <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The
* following expression: <pre> {@code
*
* Splitter.on(',').split(" foo,,, bar ,")}</pre>
*
* ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this
* is not the desired behavior, use configuration methods to obtain a <i>new</i>
* splitter instance with modified behavior: <pre> {@code
*
* private static final Splitter MY_SPLITTER = Splitter.on(',')
* .trimResults()
* .omitEmptyStrings();}</pre>
*
* <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo",
* "bar"]}. Note that the order in which these configuration methods are called
* is never significant.
*
* <p><b>Warning:</b> 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. <pre> {@code
*
* // Do NOT do this
* Splitter splitter = Splitter.on('/');
* splitter.trimResults(); // does nothing!
* return splitter.split("wrong / wrong / wrong");}</pre>
*
* <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an
* input string containing {@code n} occurrences of the separator naturally
* yields an iterable of size {@code 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 {@code [""]}
* (note: even fixed-length splitters).
*
* <p>Splitter instances are thread-safe immutable, and are therefore safe to
* store as {@code static final} constants.
*
* <p>The {@link Joiner} class provides the inverse operation to splitting, but
* note that a round-trip between the two should be assumed to be lossy.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/StringsExplained#splitter">
* {@code Splitter}</a>.
*
* @author Julien Silland
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Splitter {
private final CharMatcher trimmer;
private final boolean omitEmptyStrings;
private final Strategy strategy;
private final int limit;
private Splitter(Strategy strategy) {
this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE);
}
private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) {
this.strategy = strategy;
this.omitEmptyStrings = omitEmptyStrings;
this.trimmer = trimmer;
this.limit = limit;
}
//..
}
on
- Splitter指定分隔符的方法,如果你的字符串为"1,2,3",那么你的是分隔符就是","
public static void main(String[] args) throws Exception {
List<String> ints = Splitter.on("|").splitToList("1|2|3");
// [1, 2, 3]
System.out.println(ints);
}
split
- Splitter的切割的方法,可以通过on指定分隔符,由split指定切割的字符串。
public static void main(String[] args) throws Exception {
// [1, 2, 3]
System.out.println(Splitter.on("|").split("1|2|3"));
// 1
// 2
// 3
Splitter.on("|").split("1|2|3").forEach(System.out::println);
}
splitToList
- Splitter的切割为list的方法,可以通过on指定分隔符,由split指定切割的字符串。
public static void main(String[] args) throws Exception {
List<String> ints = Splitter.on("|").splitToList("1|2|3");
// [1, 2, 3]
System.out.println(ints);
}
trimResults
- Splitter的处理结果的前后空白的方法。
public static void main(String[] args) throws Exception {
// [1, 2, 3]
System.out.println(Splitter.on("|").trimResults().split("1 |2 | 3"));
}
omitEmptyStrings
- Splitter的去掉空串的方法。
public static void main(String[] args) throws Exception {
// [1, 2, 3]
System.out.println(Splitter.on("|").trimResults().omitEmptyStrings().split("1 |2 ||3"));
// [1 , 2 , 3]
System.out.println(Splitter.on("|").omitEmptyStrings().split("1 |2 ||3"));
}
withKeyValueSeparator
- 它主要是针对的Map的KV,返回一个MapSplitter ,基于MapSplitter以分隔符分隔,此方法用来解析url参数在合适不过了。
public static void main(String[] args) throws Exception {
Map<String, String> splitMap = Splitter.on("|").withKeyValueSeparator("=").split("name=小明|age=22");
// {name=小明, age=22}
System.out.println(splitMap);
}
Example
// 分隔转换
public static void main(String[] args) throws Exception {
String userIds = "10001,10002,a56,b123421";
List<Long> ids = Splitter.on(',').splitToList(userIds)
.stream()
.filter(StringUtils::isNumeric) // import org.apache.commons.lang3.StringUtils;
.map(Long::parseLong)
.collect(Collectors.toList());
// [10001, 10002]
System.out.println(ids);
}