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); //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#scala#kafka
用指定值代替集合中的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