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