01-guava Joiner和Splitter

Joiner

1
2
3
4
5
List<String> list = Lists.newArrayList("a", "b", "c", "d", "e");

String joinStr = Joiner.on("||").skipNulls().join(list);

//joinStr:a||b||c||d||e
1
2
3
4
5
6
7
Map<String, String> testMap = Maps.newLinkedHashMap();
testMap.put("广东", "粤语");
testMap.put("广西", "壮语");
testMap.put("北京", "普通话");
testMap.put("四川", "四川话");
String returnStr = Joiner.on("#").withKeyValueSeparator("=").join(testMap);
//returnStr:广东=粤语#广西=壮语#北京=普通话#四川=四川话

Splitter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Splitter splitter = Splitter.on('|');
Iterable<String> parts = splitter.split("1 |2|3|||");
parts.forEach(d -> System.out.println(d + "=="));

//Iterable<String> parts = splitter.split("1 |2|3|||");
1 ==
2==
3==
==
==
==

//Iterable<String> parts = splitter.trimResults().split("1 |2|3|||");
1==
2==
3==
==
==
==

//Iterable<String> parts = splitter.omitEmptyStrings().split("1 |2|3|||");
1 ==
2==
3==

//Iterable<String> parts = splitter.omitEmptyStrings().trimResults().split("1 |2|3|||");
1==
2==
3==
1
2
3
4
5
6
7
8
9
10
11
12
String startString = "广东=粤语#广西=壮语#北京=普通话#四川=四川话";
Map<String,String> testMap = Maps.newLinkedHashMap();
testMap.put("广东","粤语");
testMap.put("广西","壮语");
testMap.put("北京","普通话");
testMap.put("四川","四川话");
Splitter.MapSplitter mapSplitter =
Splitter.on("#").withKeyValueSeparator("=");
Map<String,String> splitMap =
mapSplitter.split(startString);
System.out.println("splitMap:" + splitMap);
assertThat(testMap, is(splitMap));

来源:Getting Started with Google Guava