Joiner和Splitter 算是一个比较有意思的工具类了,可以实现字符串的分割和容器的拼接
具体的使用还是比较简单的,给个例子就可以清晰看到如何使用了
Joiner使用姿势
@Test
public void testJoiner() {
List<String> list = new ArrayList<String>() {
{
add("12");
add("@#");
add("absc");
}
};
String ans = Joiner.on(",").join(list);
System.out.println("join: " + ans);
String[] strs = new String[]{"123", "456", "789", "asdf"};
ans = Joiner.on("&").join(strs);
System.out.println(ans);
Map<String, Object> params = new HashMap<String, Object>() {
{
put("key1", "123");
put("key2", 678);
put("key3", "what");
}
};
ans = Joiner.on("&").withKeyValueSeparator("=").join(params);
System.out.println("map->" + ans);
}
输出
join: 12,@#,absc
123&456&789&asdf
map->key1=123&key2=678&key3=what
Splitter使用姿势
@Test
public void testSplit() {
String ans = "key1=123&key2=678&key3=what";
Map<String, String> map =Splitter.on("&").withKeyValueSeparator("=").split(ans);
System.out.println("split map: " + map);
ans = "123&456&789&asdf";
List<String> list = Splitter.on("&").splitToList(ans);
System.out.println("split list: " + list);
}
输出
split map: {key1=123, key2=678, key3=what}
split list: [123, 456, 789, asdf]