In my last post: Solr RssResponseWriter by Extending XMLWriter, I need parse the field mapping string like: topic:title,url:link,description:description to a map.
If we have to write our own code, the code would look like below:
As described in code above, Guava provides a Joiner that can join text with a separator. Joiner also provides useful methods such as skipNulls, useForNull(nullText).
Resources
Strings Explained
Splitter Javadoc
Joiner Javadoc
Guava Splitter vs StringUtils
If we have to write our own code, the code would look like below:
public void splitOnOurOwn() { String mapStr = "topic: title, url: link, description: description "; String[] pairs = mapStr.split(","); Map<String,String> map = new HashMap<String,String>(); for (String pair : pairs) { String[] str = pair.split(":"); map.put(str[0].trim(), str[1].trim()); } System.out.println("toString: " + Objects.toString(map)); }But if we use Guava it would be just two lines:
private static MapSplitter splitter = Splitter.on(",").trimResults() .withKeyValueSeparator(Splitter.on(':').trimResults()); private static MapJoiner joinner = Joiner.on(",").withKeyValueSeparator(":"); public void guavaSplit() { String mapStr = "topic: title, url: link, description: description "; Map<String,String> map = splitter.split(mapStr.trim()); System.out.println("toString: " + Objects.toString(map)); System.out.println("join: " + joinner.join(map)); }Guava Splitter provides some other useful methods such as fixedLength, omitEmptyStrings, trimResults, limit.
As described in code above, Guava provides a Joiner that can join text with a separator. Joiner also provides useful methods such as skipNulls, useForNull(nullText).
Resources
Strings Explained
Splitter Javadoc
Joiner Javadoc
Guava Splitter vs StringUtils