Skip to content
Advertisement

From java.util.ArrayList to a dictionary in java

Im using a JBPM to make a SQL query in the DB. The sql output is return to a variable that is java.util.ArrayList. The table that im queryin is like this in MariaDB:

variable   value
math       1
physics    4
biology    10
...
sport      5
chemistry  9

The query that I’m making is SELECT * from school_data. It is returning me in a form of list like [math,1,phycics,4,biology,10…..] and only 20 elements.

Is there a way to transform the output in dictionary and then extract the values easly? I python it would be like this:

cur = connection.cursor()
cur.execute("SELECT * from school_data")
result = cur.fetchall()
query_result = dict((x, y) for x, y in result)
math=query_result['math']
physics=query_result['physics']
biology=query_result['biology']

Advertisement

Answer

Java does not have lists or dictionaries / maps as built-in data types, so it does not offer syntax or built-in operators for working with them. One can certainly perform transformations such as you describe, but it’s a matter of opinion whether it can be done “easily”. One way would be something like this:

Map<String, String> query_result = new HashMap<>();

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

String biology = query_result.get("biology");
// ...

That makes some assumptions about the data types involved, which you might need to adjust for your actual data.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement