HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Code review - parse a query to arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysqueryparsecodereview

Problem

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?

Solution

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 map = new HashMap(terms.length);

for (String term in terms)
{
    if(term.contains("="))
    {
        String[] parts = term.split("=");
        map.add(parts[0], parts[1]);
    }
}

Code Snippets

String[] parts = terms[i].split("=");
keys[i] = parts[0];
values[i] = parts[1];
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]);
    }
}

Context

StackExchange Code Review Q#2886, answer score: 4

Revisions (0)

No revisions yet.