Guava:Spiltter 拆分器

简介

Splitter 提供了各种方法来处理分割操作,如集合,字符串,对象等。

类方法说明

方法名称 方法说明
fixedLength(int length)  初始化拆分器,拆分器会将字符串分割为元素长度固定的List,最后一个元素长度不足可以直接返回.
limit(int limit)  限制拆分出的字符串数量
omitEmptyStrings()  从结果中自动忽略空字符串.
on(char separator)  初始化拆分器,参数为分隔符.
on(CharMatcher separatorMatcher)  初始化拆分器,参数为分隔符.
on(Pattern separatorPattern)  初始化拆分器,参数为分隔符.
on(String separator)  初始化拆分器,参数为分隔符.
onPattern(String separatorPattern)  返回一个拆分器,它将与给定模式(正则表达式)匹配的任何子序列视为分隔符.
split(CharSequence sequence)  对Stirng通过拆分器进行拆分,返回一个Iterable.
splitToList(CharSequence sequence)  将序列拆分为字符串组件并将其作为不可变列表返回.
trimResults()  修饰拆分器,拆分器做拆分操作时,会对拆分的元素做trim操作(删除元素头和尾的空格),相当于 trimResults(CharMatcher.whitespace()).
trimResults(CharMatcher trimmer)  修饰拆分器,拆分器做拆分操作时,会删除元素头尾charMatcher匹配到的字符.
withKeyValueSeparator(char separator)  初始化一个Map拆分器,拆分器对String拆分时,separator为key和value之间的分隔符.
withKeyValueSeparator(Splitter keyValueSplitter)  初始化一个Map拆分器,拆分器对String拆分时,separator为key和value之间的分隔符.
withKeyValueSeparator(String separator)  初始化一个Map拆分器,拆分器对String拆分时,separator为key和value之间的分隔符.

使用Demo

import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import org.junit.Test;

import java.util.List;

/**
 * 字符串拆分
 */
public class SplitterTest{

    @Test
    public void splitter() {
        //1.字符串转集合
        //1.1按指定字符分割
        Splitter on = Splitter.on("!");
        List list = on.splitToList("hello!world");
        System.out.println(list);   // [hello, world]

        //过滤空
        List list2 = Splitter.on("!").omitEmptyStrings().splitToList("hello ! world!!!!!!");
        System.out.println(list2);           // [hello ,  world]

        //分割限制
        List list4 = Splitter.on("#").limit(3).splitToList("hello#world#java#google#scala");
        System.out.println(list4);//[hello, world, java#google#scala]

        //1.2按长度分割
        List list5 = Splitter.fixedLength(3).splitToList("aaabbbcccddde");
        System.out.println(list5);//[aaa, bbb, ccc, ddd, e]

        //1.3正则匹配
        List list6 = Splitter.onPattern("[.|,]").splitToList("apple.banana,,orange,,.");
        System.out.println(list6);//[apple, banana, , orange, , , ]

        //1.4去除指定字符
        //过滤空
        List list3 = Splitter.on("!").trimResults().splitToList("hello ! world!  !!!!!");
        System.out.println(list3);           // [hello ,  world]
        //过滤空指定字符
        String str1 = "~?~this, is~~ , , random , text,";
        List result = Splitter.on(',')
                .trimResults(CharMatcher.anyOf("~? "))//表示去除~,?," "
                .splitToList(str1);
        System.out.println(result);     // [this, is, random, text]
    }

}

你可能感兴趣的:(Guava,常用,guava,java)