Split string into key-value pairs

python split string into key value pairs
convert key value pair to string javascript
split string to key and value
key-value string
java string get key value
java map split string
es6 split string into object
split string and store in map java

I have a string like this:

pet:cat::car:honda::location:Japan::food:sushi

Now : indicates key-value pairs while :: separates the pairs. I want to add the key-value pairs to a map.

I can achieve this using:

Map<String, String> map = new HashMap<String, String>();
String test = "pet:cat::car:honda::location:Japan::food:sushi";
String[] test1 = test.split("::");

for (String s : test1) {
    String[] t = s.split(":");
    map.put(t[0], t[1]);
}

for (String s : map.keySet()) {
    System.out.println(s + " is " + map.get(s));
}

But is there an efficient way of doing this?


I feel the code is inefficient because I have used 2 String[] objects and called the split function twice. Also, I am using t[0] and t[1] which might throw an ArrayIndexOutOfBoundsException if there are no values.

You could do a single call to split() and a single pass on the String using the following code. But it of course assumes the String is valid in the first place:

    Map<String, String> map = new HashMap<String, String>();
    String test = "pet:cat::car:honda::location:Japan::food:sushi";

    // split on ':' and on '::'
    String[] parts = test.split("::?");

    for (int i = 0; i < parts.length; i += 2) {
        map.put(parts[i], parts[i + 1]);
    }

    for (String s : map.keySet()) {
        System.out.println(s + " is " + map.get(s));
    }

The above is probably a little bit more efficient than your solution, but if you find your code clearer, then keep it, because there is almost zero chance such an optimization has a significant impact on performance, unless you do that millions of times. Anyway, if it's so important, then you should measure and compare.

EDIT:

for those who wonder what ::? means in the above code: String.split() takes a regular expression as argument. A separator is a substring that matches the regular expression. ::? is a regular expression which means: 1 colon, followed by 0 or 1 colon. It thus allows considering :: and : as separators.

Python | Convert key-value pair comma separated string into dictionary. Given a string res = dict (item.split( "=" ) for item in ini_string1.split( ", " )). # Printing  Split string into key-value pairs. Ask Question Asked 4 years, This also might work faster than JDK String.split as it does not create a regexp for "::".

Using Guava library it's a one-liner:

String test = "pet:cat::car:honda::location:Japan::food:sushi";
Map<String, String> map = Splitter.on( "::" ).withKeyValueSeparator( ':' ).split( test );
System.out.println(map);

The output:

{pet=cat, car=honda, location=Japan, food=sushi}

This also might work faster than JDK String.split as it does not create a regexp for "::".

Update it even handles correctly the corner case from the comments:

String test = "pet:cat::car:honda::location:Japan::food:sushi:::cool";
Map<String, String> map = Splitter.on( "::" ).withKeyValueSeparator( ':' ).split( test );
System.out.println(map);

The output is:

{pet=cat, car=honda, location=Japan, food=sushi, =cool}

Note: We pass the separator within pairs to this method. The on() method receives the separator between pairs of keys and values. Below examples key-​value pairs. String value Using Splitter to parse key-value separators. // This returns a  Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task.

To split a string into key value pairs (i.e dict) the following can be used, >>> string = "abc=123,xyz=456" >>> dict(x.split('=') for x in string.split('  First, we split on the outer delimiter (i.e. the semi-colon). From the resulting array, we select by splitting again, this time on =. The resulting array of arrays is converted to a dictionary by specifying that the first item is to become the key and the second is to become the value (the identifier kvp stands for “key-value pair”).

Try this code - see the comments for an explanation:

HashMap<String,String> hmap = new HashMap<>();
String str="abc:1::xyz:2::jkl:3";
String straraay[]= str.split("::?");

for(int i=0;i<straraay.length;i+=2) {
    hmap.put(straraay[i],straraay[i+1]);
}

for(String s:straraay){
    System.out.println(hmap.values()); //for Values only
    System.out.println(hmap.keySet()); //for keys only if you want to more clear
}

Because each key-value pair must be on a separate line, here-strings are often cmdlet converts a string that contains one or more key and value pairs into a  Here is a nice little SQL function that could help you extract key value pairs from a string. This can be really helpful in parsing log statements/audit logs stored in SQL servers. This can be really helpful in parsing log statements/audit logs stored in SQL servers.

I don't know this is best approach or not but i think this is another way of doing same thing without using split method twice

Map<String, String> map = new HashMap<String, String>();
String test = "pet:cat::car:honda::location:Japan::food:sushi";
String[] test1 = test.replaceAll("::",":").split(":");
for(int i=0;i<test1.length;i=i+2)
{
     map.put(test1[i], test1[i+1]);
}

for (String s : map.keySet()) {
    System.out.println(s + " is " + map.get(s));
}

Hope it will help :)

asp.net c# examples. uwp tutorials. linq, array, ajax, xml, silverlight, xaml, string, list, date time, object, validation, xpath, xslt and many more. Python - Split a String into a Dictionary. Written by Rick Donato on 22 March 2015. Posted in Python. To split a string into key value pairs (i.e dict) the following can be used, >>> string = "abc=123,xyz=456" >>> dict(x.split('=') for x in string.split(',')) {'xyz': '456', 'abc': '123'}

Two ways of initializing a collection of key-value pairs: Very often, a string contains lots of text and we want to split the text into separate lines; Lines may be​  How to split key value pair string to hash in Perl By Gowri Shankar Balasubramaniam June 10, 2018 PERL Leave a Comment on How to split key value pair string to hash in Perl Perl is highly advanced programming language in order to process with strings.

the_dict = {}; the_string = 'a=1;b=2;c=3;'; for pair in the_string.split(';'):; if pair: key, value in pair.split('='); the_dict[key.strip()] = value.strip() In Python, if I use a loop to concatenate many strings together into a single output  The split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

Your string looks very similar to the YAML syntax. Indeed it is This will unpack the line.split and convert them into a key, value pair for you We'll convert collections into a String with the Joiner and we'll split a String into a collection with the Splitter. 2. Convert List into String Using Joiner

Comments
  • Can you explain whx you think it isn't efficient? Btw, this is not codereview.stackexchange.com, you should try it there.
  • First thing is I am newbie in Java and always thought there was an easier way of doing the things I do. Next is I have used 2 String array objects and called the split function twice. Also I am using t[0] and t[1] which might throw an ArrayIndexOutOfBounds Exception if there are not values.
  • This method is absolutely fine.
  • @Tom I see a lot of question which ask for a better way of doing things. And thats why I asked the same here.
  • @ViChU can you add that to your question? If you have concerns about a certain algorithm, you should explain it, so the one who answers question can address that.
  • wow ! this takes care of everything which I thought was inefficient. But one more thing. I changed the string to this "location:Japan::food:sushi:::cool" such that the value cool has no key. But still the output is this: is cool location is Japan food is sushi
  • just found that the key for the value 'cool' is just an empty String.
  • It might be good to briefly explain what ::? means (and mention the obvious alternative :|:: for those with the same problem, but different separators).
  • Nice ! Thanks for this.I don't know if this is the most efficient but this is something that I should keep in mind when dealing with strings like these.
  • I think this part of the code withKeyValueSeparator( ':' ) should be changed with withKeyValueSeparator( ":" ) since the method withKeyValueSeparator is taking String as an argument
  • Well, to answer your question. There are still many organizations which have not adapted to the latest standards. In my case , this data comes the POS system. There are a huge number of retail stores in America and each retail store has many POS counters and each transaction in the counter sends this data. And by data , it does not include just this string. This string is like a single line in a 10000 line xml file. So there is a requirement to keep the code as efficient as possible. And hence this question arose in my mind :)