Joiner:
List<String> stringList = new ArrayList<String>();
stringList.add("aa");
stringList.add("bb");
System.out.println(new JoinerTest().buildString(stringList, "/"));
System.out.println(Joiner.on("|").skipNulls().join(stringList));
System.out.println(Joiner.on("|").useForNull("no value").join(stringList));
System.out.println(Joiner.on("/").join("aa", "bb", ""));
// FileWriter fileWriter = new FileWriter(new File("/Users/zj/aa.txt"));
// Joiner joiner = Joiner.on("#").useForNull(" ");
// //returns the FileWriter instance with the values
// //appended into it
// joiner.appendTo(fileWriter, stringList);
// fileWriter.flush();
// fileWriter.close();
Map<String,String> testMap = Maps.newLinkedHashMap();
testMap.put("Washington D.C","Redskins");
testMap.put("New York City","Giants");
testMap.put("Philadelphia","Eagles");
testMap.put("Dallas","Cowboys");
MapJoiner mapJoiner = Joiner.on("#").withKeyValueSeparator("=");
System.out.println(mapJoiner.join(testMap));
Splitter:
System.out.println(Splitter.on('|').trimResults().split("foo|bar ||baz "));
String startString = "Washington D.C=Redskins#New York" +
"City=Giants#Philadelphia=Eagles#Dallas=Cowboys";
Map<String,String> testMap = Maps.newLinkedHashMap();
testMap.put("Washington D.C","Redskins");
testMap.put("New York City","Giants");
testMap.put("Philadelphia","Eagles");
testMap.put("Dallas","Cowboys");
Splitter.MapSplitter mapSplitter = Splitter.on("#").withKeyValueSeparator("=");
Map<String,String> splitMap = mapSplitter.split(startString);
MapJoinner和MapSplitter
对于MapJoinner和MapSplitter的最好案例就是url的param编码。
MapJoinner
题目:
生产一个查询id: 123,name: green的学生信息的url。
利用Guava的MapJoinner的代码如下:
1 |
|
这里采用了on传入map item之间分隔符,以及withKeyValueSeparator传递map项key/value之间的分隔符。所以能够很简单的实现,不用我们在去实现一个的for循环代码。
MapSplitter
题目:
对url中的查询字符串"id=123&name=green"进行分割
利用Guava的MapSplitter的代码如下:
1 |
|
这里同样利用on传入字符串的第一分隔符,withKeyValueSeparator传入项的分隔符,产生map的key/value项,其结果是一个{id=123, name=green}的Map对象。