Guava 工具类之joiner的使用
joiner主要用于对字符串的连接,也可用于对map中key value的连接
public class JoinerTest { private static final List<String> list1 = Arrays.asList ("google","guava","java","scala","kafka"); private static final List<String> list2 = Arrays.asList ("google","guava","java",null,"scala","kafka"); public static void main(String[] args) throws IOException { //1.用指定的字符连接 String join = Joiner.on("#").join(list1); System.out.println("用 # 号连接的字符串是:"+join); //输出结果:google#guava#java#scala#kafka
//2.跳过连接中的null值 String joinNull = Joiner.on("#").skipNulls().join(list2); System.out.println("用 # 号连接的字符串,跳过中间的null值:"+joinNull); //3.有null值存在时用指定值代替 String joinUseForNull = Joiner.on("#").useForNull("DEFAULT").join(list2); System.out.println("用指定值代替集合中的null值:"+joinUseForNull); //4.把集合变成一个stringBuilder 或者stringBuffer StringBuilder builder = Joiner.on("#").useForNull("DEFAULT").appendTo(new StringBuilder(), list2); StringBuffer buffer = Joiner.on("#").useForNull("DEFAULT").appendTo(new StringBuffer(), list2); System.out.println("拼接成的 builder是:"+builder); System.out.println("拼接成的buffer是:"+buffer); //5.对于map中key value的分隔 Map<String, String> map = new HashMap<String, String>(); map.put("hello", "java"); map.put("scala", "guava"); String joinMap = Joiner.on("#").withKeyValueSeparator("=").join(map); System.out.println("key value 的分隔符:"+joinMap); } }
//打印结果
用指定值代替集合中的null值:google#guava#java#DEFAULT#scala#kafka
拼接成的 builder是:google#guava#java#DEFAULT#scala#kafka
拼接成的buffer是:google#guava#java#DEFAULT#scala#kafka
key value 的分隔符:scala=guava#hello=java
由于本人是自己学习总结出来的,有不足之处,请各位看官批评指出,我将及时改正,以提高知识总结的正确性和严谨性,为大家学习提供方便!!!
如若转载,请注明出处!!!