title: 从一行代码到Guava Joiner tags:
- Guava
- Joiner
- MapJoiner
- Sonar categories: guava date: 2017-11-16 15:13:32
背景
代码中的到处散乱着如下的代码
开发到处拷贝粘贴导致,事实上某些情况下开发还需要处理最后一个分隔符
解决方案
StringBuilder
Sonar给出的方案
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.
Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.
For example:
// This is bad String s = ""; for (int i = 0; i < field.length; ++i) { s = s + field[i]; } // This is better StringBuffer buf = new StringBuffer(); for (int i = 0; i < field.length; ++i) { buf.append(field[i]); } String s = buf.toString();复制代码
对于栈上私有对象来说应当考虑StringBuilder更好
Joiner
当然我们更好的方法是使用Guava 的Joiner
比如
Listlist = Lists.transform(tbRoleOrgList, new Function () { @Nullable @Override public String apply(@Nullable TbRoleOrg input) { return input == null ? null : input.getOrgId(); } }); Joiner joiner = Joiner.on(",").skipNulls(); return joiner.join(list);复制代码
joiner 提供了比较多的api
当然还有MapJoiner也是很常用的工具类
Joiner.MapJoiner mapJoiner = Joiner.on("&").withKeyValueSeparator("="); return mapJoiner.join(errorMap);复制代码
十分方便【更重要的是Joiner和MapJoiner是线程安全的~】
某些拼接URL的场景十分合用!