public static void main(String[] args) {System.out.println("---------------- ");/*** Google Guava提供了Joiner类专门用来连接String。* 譬如说有个String数组,里面有"a","b","c",* 我们可以通过使用StringBuilder来创建String "a,b,c"。*/Joiner joiner = Joiner.on(";");String str1 = joiner.join(new String[]{"a","b","c"});System.out.println(" str1 : " + str1);/*** 当然Joiner.join还提供了参数为Iterable的overload形式。也就是说你可以传各种List和Set。* 如果被连接String里面要过滤null,可以这样*/Joiner joiner2 = Joiner.on(";").skipNulls(); //过滤nullString str2 = joiner2.join(new String[]{"a","b",null,"c"});List<String> list = new ArrayList<String>();list.add("1");list.add("2");list.add(null);list.add("3");String str21 = joiner2.join(list);System.out.println(" str2 : " + str2);System.out.println(" str21 : " + str21);/*** 如果对null进行替换操作*/Joiner joiner3 = Joiner.on(";").useForNull("!");String str3 = joiner3.join(new String[]{"a","b",null,"c"});System.out.println(" str3 : " + str3);/*** Joiner还提供了appendTo函数,对传入的StringBuider作处理*/Joiner joiner4 = Joiner.on(";");StringBuilder ab = new StringBuilder("start : ");StringBuilder str4 = joiner4.appendTo(ab, new String[]{"a","b","c"});System.out.println(" str4 : " + str4.toString());/*** MapJoiner类也利用了Joiner提供的Map的join功能*/Map<Integer, String> map = new HashMap<Integer, String>();map.put(1, "a");map.put(2, "b");MapJoiner joiner5 = Joiner.on(";").withKeyValueSeparator("→");String str5 = joiner5.join(map);System.out.println(" str5 : " + str5);//url拼接Map<String, Object> map2 = new HashMap<String, Object>();map2.put("param1", "HAN");map2.put("param2", 2);MapJoiner joiner6 = Joiner.on("&").withKeyValueSeparator("=");String str6 = joiner6.join(map2);System.out.println(" str6 : " + str6);String str7 = joiner6.join(ImmutableMap.of("id","123","name","green"));System.out.println(" str7 : " + str7);//分割final Map<String, String> join = Splitter.on("&").withKeyValueSeparator("=").split("id=123&name=green¶m1=HAN¶m2=2");System.out.println(" map :" + join.toString());}
转载于:https://blog.51cto.com/hanchaohan/1931272