Hot questions for Splitting the Data in Guava

Top 10 Java Open Source / Guava / Splitting the Data

Parse a string with key=value pair in a map?

Question: I have below String which is in the format of key1=value1, key2=value2 which I need to load it in a map (Map<String, String>) as key=value so I need to split on comma , and then load cossn as key and 0 its value.

String payload = "cossn=0, itwrqm=200006033213";
Map<String, String> holder =
          Splitter.on(",").trimResults().withKeyValueSeparator("=").split(payload);

I am using Splitter here to do the job for me but for some cases it is failing. For some of my strings, value has some string with equal sign. So for below string it was failing for me:

String payload = "cossn=0, abc=hello/=world";

How can I make it work for above case? For above case key will be abc and value should be hello/=world. Is this possible to do?

Answer: you can add a number to say how many splits you want just add a 2 to split

public class HelloWorld{

     public static void main(String []args){
        HashMap<String, String> holder = new HashMap();
        String payload = "cossn=0, abc=hello/=world";
        String[] keyVals = payload.split(", ");
        for(String keyVal:keyVals)
        {
          String[] parts = keyVal.split("=",2);
          holder.put(parts[0],parts[1]);
        }

     }
}

You can do this same thing with the Splitter API directly:

Map<String, String> result = Splitter.on(',')
    .trimResults()
    .withKeyValueSeparator(
        Splitter.on('=')
            .limit(2)
            .trimResults())
    .split(input);

Guava: Splitter and considering Escaping?

Question: I am interested in the Splitting possibility of Guava:

Splitter.on("|").split("foo|bar|baz");
// => "foo", "bar", "baz"

This works correctly.

What now if I want to split on "|" but not between "[" and "]":

Splitter.on(something).split("foo|ba[r|ba]z");
// => "foo", "ba[r|ba]z"

Answer: The proper way to deal with this is to make a parser. It's really easy nowadays, just use a parser combinator, such as JParsec. You'll get something like this:

class ParserFactory {

    Parser escapedSequence() {
        return Parsers.between(Scanners.string("["), 
            Scanners.anyCharacterButNot("]"), Scanners.string("]"));
    }

    Parser chunk() {
        return Parsers.or(escapedSequence(), Scanners.anyCharacterButNot("|"));
    }

    Parsers wholeThing() {
        return Parsers.separatedBy(chunk().plus(), Scanners.string("|"));
    }
}