Joiner

文章目录

  • Joiner

Joiner

Google Guava提供了Joiner类专门用来连接String。

String数组,里面有"a",“b”,“c”,我们可以通过使用StringBuilder来创建String "a,b,c"也可以传入list,set


//result = "a;b;c"
result = Joiner joiner = Joiner.on(";").joiner.join(new String[}{"a","b","c"})); 

如果被连接String里面要过滤null,可以这样:

//result = "a;c"
result = Joiner.on(";").useForNull("!").joiner.join(new String[]{"a",null,"c"}));

对null进行替换

//result = "a;!;c"
result = Joiner.on(";").useForNull("!").joiner.join(new String[]{"a",null,"c"}));

appendTo,对传入的StringBuilder作处理:

//result = start: a;b;c
StringBuilder ab = new StringBuilder("start: ");  
result = Joiner.on(";").joiner.appendTo(ab, new String[]{"a","b","c"}).toString(); 

MapJoiner类也利用Joiner提供了Map的join功能:

//result = "1->a;2->b"
Map map = new HashMap();  
map.put(1, "a");  
map.put(2, "b");  
MapJoiner joiner = Joiner.on(";").withKeyValueSeparator("->");  
result = joiner.join(map);

请不要这样使用
// Bad! Do not do this!  
Joiner joiner = Joiner.on(',');  
joiner.skipNulls(); // does nothing!  //joiner.skipNulls();会返回一个匿名对象。
return joiner.join("wrong", null, "wrong");

你可能感兴趣的:(java)