Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a string of key/value pairs in Java

I have a String that's formatted like this:

"key1=value1;key2=value2;key3=value3"

for any number of key/value pairs.

I need to check that a certain key exists (let's say it's called "specialkey"). If it does, I want the value associated with it. If there are multiple "specialkey"s set, I only want the first one.

Right now, I'm looking for the index of "specialkey". I take a substring starting at that index, then look for the index of the first = character. Then I look for the index of the first ; character. The substring between those two indices gives me the value associated with "specialkey".

This is not an elegant solution, and it's really bothering me. What's an elegant way of finding the value that corresponds with "specialkey"?

like image 703
user438293456 Avatar asked Mar 13 '12 01:03

user438293456


People also ask

How do you find the key-value pair of a string?

for(String kvPair: kvPairs) { String[] kv = kvPair. split("="); String key = kv[0]; String value = kv[1]; // Now do with key whatever you want with key and value... if(key. equals("specialkey")) { // Do something with value if the key is "specialvalue"... } }

How do you find a specific string in Java?

You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.

How do you find if a string contains a character in Java?

lang. String. contains() method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false.

How do you use key value pairs in Java?

Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.


1 Answers

I would parse the String into a map and then just check for the key:

String rawValues = "key1=value1;key2=value2;key3=value3";
Map<String,String> map = new HashMap<String,String>();
String[] entries = rawValues.split(";");
for (String entry : entries) {
  String[] keyValue = entry.split("=");
  map.put(keyValue[0],keyValue[1]);
}

if (map.containsKey("myKey")) {
   return map.get("myKey");
}
like image 136
Mike Sickler Avatar answered Sep 21 '22 14:09

Mike Sickler