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(); //過濾null String 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()); }