Google Guava提供了Joiner类专门用来连接String。
譬如说有个String数组,里面有"a","b","c",我们可以通过使用StringBuilder来创建String "a,b,c"。
Joiner提供了这一类的功能。
譬如:
1. Joiner joiner = Joiner.on(";");
2. assertEquals("a;b;c", joiner.join(new String[}{"a","b","c"}));
当然Joiner.join还提供了参数为Iterable的overload形式。也就是说你可以传各种List和Set。
如果被连接String里面要过滤null,可以这样:
1. Joiner joiner = Joiner.on(";").skipNulls();
2. assertEquals("a;c", joiner.join(new String[]{"a",null,"c"}));
或者对null进行替换操作:
1. Joiner joiner = Joiner.on(";").useForNull("!");
2. assertEquals("a;!;c", joiner.join(new String[]{"a",null,"c"}));
Joiner还提供了appendTo函数,对传入的StringBuilder作处理:
1. Joiner joiner = Joiner.on(";");
2. StringBuilder ab = new StringBuilder("start: ");
3. assertEquals("start: a;b;c", joiner.appendTo(ab, new String[]{"a","b","c"}).toString());
除此之外,相关的MapJoiner类也利用Joiner提供了Map的join功能:
1. Map<Integer, String> map = new HashMap<Integer, String>();
2. map.put(1, "a");
3. map.put(2, "b");
4. MapJoiner joiner = Joiner.on(";").withKeyValueSeparator("->");
5. assertEquals("1->a;2->b", joiner.join(map));
static final来用没问题。但是这样的话,正如javadoc所举的例子:
第1行的Joiner对象就是第3行的对象,第2行的skipNulls()其实是返回一个Joiner的一个匿名子类,而对之前的joiner对象没有影响,所以第3行的Joiner对象根本没有skip null的功能。
// Bad! Do not do this! Joiner joiner = Joiner.on(','); joiner.skipNulls(); // does nothing! return joiner.join("wrong", null, "wrong");