导入maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
使用实例
Joiner : 把list或者map转成string
public static void main(String[] args) {
//join,
List<String> stringList = Arrays.asList("1", "2", "4");
String result = Joiner.on('#').join(stringList);
System.out.println(result); //1#2#4
//过滤掉null值,
List<String> stringList2 = Arrays.asList("1", "2", "4", null);
result = Joiner.on('$').skipNulls().join(stringList2);
System.out.println(result); //1$2$4
//用默认字符替换null,结果=1$2$4$Y
result = Joiner.on('$').useForNull("Y").join(stringList2);
System.out.println(result);//1$2$4$Y
//append to, 返回指定的stringBuilder
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder1 = Joiner.on('%').appendTo(stringBuilder, stringList);
System.out.println(stringBuilder == stringBuilder1); //true
//java8的实现
String string = stringList2.stream().filter(s -> s != null).collect(joining("#"));
System.out.println(string);
//map的join
Map<String, String> map = new HashMap<>();
map.put("1", "2");
map.put("2", "4");
//key和value使用=分隔,两个对象之间使用$分隔
String s = Joiner.on("$").withKeyValueSeparator("=").join(map);
System.out.println(s);//1=2$2=4
}
Splitter: 把string转化为list或者map
//Splitter
String s1 = "1%2%3%4%6%7";
List<String> strings = Splitter.on('%').splitToList(s1);
System.out.println(strings.toString());//[1, 2, 3, 4, 6, 7]
//去掉空格
strings = Splitter.on("$").omitEmptyStrings().splitToList("4 $$ e");
System.out.println(strings.toString());//[4 , e]
//string进行trim
strings = Splitter.on("$").trimResults().omitEmptyStrings().splitToList("4 $$ e");
System.out.println(strings.toString());//[4, e]
//固定长度split
strings = Splitter.fixedLength(4).splitToList("aaaabbbbccccdddd");
System.out.println(strings.toString());//[aaaa, bbbb, cccc, dddd]
//限制分隔出来的list的大小
strings = Splitter.on("#").limit(3).splitToList("hello#worled#rerere#retrtrtr");
System.out.println(strings.toString());//[hello, worled, rerere#retrtrtr]
//正则表达式进行分隔
strings = Splitter.onPattern("\\|").trimResults().omitEmptyStrings().splitToList("hello|world|3444");
System.out.println(strings);//[hello, world, 3444]
//string转map
Map<String, String> map1 = Splitter.on("%").trimResults()
.omitEmptyStrings().withKeyValueSeparator("=").split("hello=3%world=4");
System.out.println(map1);//{hello=3, world=4}