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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
public static void main(String[] args) {
System.out.println( "---------------- " );
/**
* Google Guava提供了Joiner类专门用来连接String。
* 譬如说有个String数组,里面有"a","b","c",
* 我们可以通过使用StringBuilder来创建String "a,b,c"。
*/
Joiner joiner = Joiner.on( ";" );
String str1 = joiner.join( new String[]{ "a" , "b" , "c" });
System.out.println( " str1 : " + str1);
/**
* 当然Joiner.join还提供了参数为Iterable的overload形式。也就是说你可以传各种List和Set。
* 如果被连接String里面要过滤null,可以这样
*/
Joiner joiner2 = Joiner.on( ";" ).skipNulls(); //过滤null
String str2 = joiner2.join( new String[]{ "a" , "b" , null , "c" });
List<String> list = new ArrayList<String>();
list.add( "1" );
list.add( "2" );
list.add( null );
list.add( "3" );
String str21 = joiner2.join(list);
System.out.println( " str2 : " + str2);
System.out.println( " str21 : " + str21);
/**
* 如果对null进行替换操作
*/
Joiner joiner3 = Joiner.on( ";" ).useForNull( "!" );
String str3 = joiner3.join( new String[]{ "a" , "b" , null , "c" });
System.out.println( " str3 : " + str3);
/**
* Joiner还提供了appendTo函数,对传入的StringBuider作处理
*/
Joiner joiner4 = Joiner.on( ";" );
StringBuilder ab = new StringBuilder( "start : " );
StringBuilder str4 = joiner4.appendTo(ab, new String[]{ "a" , "b" , "c" });
System.out.println( " str4 : " + str4.toString());
/**
* MapJoiner类也利用了Joiner提供的Map的join功能
*/
Map<Integer, String> map = new HashMap<Integer, String>();
map.put( 1 , "a" );
map.put( 2 , "b" );
MapJoiner joiner5 = Joiner.on( ";" ).withKeyValueSeparator( "→" );
String str5 = joiner5.join(map);
System.out.println( " str5 : " + str5);
//url拼接
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put( "param1" , "HAN" );
map2.put( "param2" , 2 );
MapJoiner joiner6 = Joiner.on( "&" ).withKeyValueSeparator( "=" );
String str6 = joiner6.join(map2);
System.out.println( " str6 : " + str6);
String str7 = joiner6.join(ImmutableMap.of( "id" , "123" , "name" , "green" ));
System.out.println( " str7 : " + str7);
//分割
final Map<String, String> join = Splitter.on( "&" ).withKeyValueSeparator( "=" ).split( "id=123&name=green¶m1=HAN¶m2=2" );
System.out.println( " map :" + join.toString());
}
|
本文转自韩立伟 51CTO博客,原文链接:http://blog.51cto.com/hanchaohan/1931272,如需转载请自行联系原作者