Google Guava之Splitter

简介: 我们上篇文章讲述了Joiner相关API使用,其中提到了Splitter,它与Joiner操作相反,它是根据给定的分隔符,把一个字符串分隔成若个子字符串,那么本篇我们来看看Splitter都有哪些操作的方式。

前言

iShot2022-12-06 02.24.29.png
我们上篇文章讲述了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);
    }

目录
相关文章
|
存储 缓存 算法
Google Guava之RateLimiter
在日常开发中,限流是高并发系统的三把守护利器之一,它的另外两个好兄弟缓存、降级下次再说。而限流在绝大多数场景中用来限制并发和请求量,像秒杀之类的高流量业务的场景,都能见到它的身影,所以它就是保护系统和下游的业务系统不被流量冲垮的利器。
325 6
Google Guava之RateLimiter
|
4月前
Google Guava ListeningExecutorService
Google Guava ListeningExecutorService
28 0
|
6月前
|
Java 数据库连接
提升编程效率的利器: 解析Google Guava库之IO工具类(九)
提升编程效率的利器: 解析Google Guava库之IO工具类(九)
|
6月前
|
缓存 Java Maven
深入解析Google Guava库与Spring Retry重试框架
深入解析Google Guava库与Spring Retry重试框架
|
6月前
|
监控 安全 算法
提升编程效率的利器: 解析Google Guava库之RateLimiter优雅限流(十)
提升编程效率的利器: 解析Google Guava库之RateLimiter优雅限流(十)
|
6月前
|
缓存 安全 Java
提升编程效率的利器: 解析Google Guava库之集合工具类-50个示例(八)
提升编程效率的利器: 解析Google Guava库之集合工具类-50个示例(八)
|
6月前
|
缓存 算法 Java
提升编程效率的利器: 解析Google Guava库之常用工具类-40个示例(七)
提升编程效率的利器: 解析Google Guava库之常用工具类-40个示例(七)
|
6月前
|
存储
提升编程效率的利器: 解析Google Guava库之集合篇RangeMap范围映射(六)
提升编程效率的利器: 解析Google Guava库之集合篇RangeMap范围映射(六)
提升编程效率的利器: 解析Google Guava库之集合篇RangeSet范围集合(五)
提升编程效率的利器: 解析Google Guava库之集合篇RangeSet范围集合(五)
|
6月前
|
存储 安全 Java
提升编程效率的利器: 解析Google Guava库之集合篇Table二维映射(四)
提升编程效率的利器: 解析Google Guava库之集合篇Table二维映射(四)