Search code examples
javaspringspring-jdbc

Spring JDBC obtaining a list of maps


probably something super simple. I'd like to retrieve two sets of key (String) and value(double) from a simple query which returns one row with two columns.

There must be a cleaner way to do it than what I have below - that's 10 lines to get the job done, which seems overkill. Any recommendation what to use instead? Thanks!

List<Map<String, Double>> RecordList = namedParameterJdbcTemplate.query(Queries.GET_DATASET(),
                getParsedQuery(request), resultSet -> {
                    List<Map<String, Double>> list = new ArrayList();
                    HashMap mMap = new HashMap();
                    mMap.put("this_year", resultSet.getDouble("this_year"));
                    list.add(mMap);
                    mMap = new HashMap();
                    mMap.put("last_year", resultSet.getDouble("last_year"));
                    list.add(mMap);
                    return list;
                });

Solution

  • I would use a MutablePair from Apache Commons. You can find javadoc here:

    With that approach you could keep this_year in the L, and last_year on R. L meaning left object and R right object.

    You could replace the code with something like that:

    return MutablePair.of(resultSet.getDouble("this_year"),resultSet.getDouble("last_year")));
    

    If you prefer not to use the Apache Commons, have a look at some alternatives: