5
\$\begingroup\$

I have a query like this "abc=1, def=2, ghi=3" and I need to parse it into arrays like this keys = [abc, def, ghi] and values = [1,2,3]

currently my code is like this

String[] terms = query.split(",");
int termsCount = terms.length;
String[] keys = new String[termsCount];
String[] values = new Object[termsCount];

for(int i=0; i<termsCount; i++)
{
    if(terms[i].contains("="))
    {
        keys[i] = terms[i].split("=")[0];
        values[i] = terms[i].split("=")[1];
    }
}

sometimes, the query might be empty or may not be well formed - I need to take care of that scenarios too.

Am I doing this right? Is there a better way to do this?

\$\endgroup\$
1
  • \$\begingroup\$ String[] values = new Object[termsCount]; should be String[] values = new String[termsCount];. Alternatively, you could chuck the whole arrays thing and do what the posters below suggest. \$\endgroup\$
    – Eva
    Jan 16, 2013 at 22:00

2 Answers 2

4
\$\begingroup\$

The code as it is, is fine. The biggest point is that you should perform the .split("=") only once:

String[] parts = terms[i].split("=");
keys[i] = parts[0];
values[i] = parts[1];

However there is a more general point: Why are you using arrays?

It's very unusual to use arrays at all in Java, especially in this case where you say yourself the input my be not well formed, possibly leaving you with gaps in the array, which you'll need to work around later. You should at least use Lists. Or even more fitting would be a Map (if the "keys" are unique):

String[] terms = query.split(",");
Map<String, String> map = new HashMap<String, String>(terms.length);

for (String term in terms)
{
    if(term.contains("="))
    {
        String[] parts = term.split("=");
        map.add(parts[0], parts[1]);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Wow, simultaneous post. :) +1, the map might make more sense, depending on the context. \$\endgroup\$ Jun 9, 2011 at 15:36
1
\$\begingroup\$

No reason to split twice. Split once and store the result. Also better do an additional check after splitting.

String[] split = terms[ i ].split( "=" );
if ( split.length == 2 )
{
    ...
}

Lastly, I wouldn't use an array to store the results in. As you said, it might not be filled up entirely since some values might be parsed incorrectly. Use a generic List<RetrievedValue> to store the results in. RetrievedValue could be a simple class holding both values.

\$\endgroup\$
1
  • \$\begingroup\$ Good point about checking the split length. I should have though of that. \$\endgroup\$
    – RoToRa
    Jun 10, 2011 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.