Search code examples
javaarrayslistjava-streamnamedparameterjdbctemplate

Convert from a list to an array of `SqlParameterSource`, i.e. convert a list to an array of maps


I have a list of entities which I want to relate to another entity using JDBC named template. For that, I am inserting the ID pairs on the join table using a batch update operation, but the problem is that the way I have found to generate an array of SqlParameterSource is a little bit clunky. Is there any way of doing this with a stream instead?

// Create an array of the size of the fruit list.
final SqlParameterSource[] fruitParameters = new SqlParameterSource[tree.getFruits().size()];

// Get all the fruits to iterate through.
final List<Fruit> fruits = tree.getFruits();

// Fill the array with the parameter sources.
for (int i = 0; i < fruitIds.length; i++) {
    final var fruit = fruits.get(i);

    final var parameters = new MapSqlParameterSource();
    parameters.addValue("fruit_id", fruit.getId());
    parameters.addValue("tree_id", tree.getId());

    fruitParameters[i] = parameters;
}

I think the problem boils down to converting a list to an array of maps.


Solution

  •  fruits.stream().map(fruit-> {
            var parameters = new MapSqlParameterSource();
            parameters.addValue("fruit_id", fruit.getId());
            parameters.addValue("tree_id", tree.getId());
            return parameters;
        }).toArray(SqlParameterSource[]::new);
    

    if you can create method that take Fruit object and return MapSqlParameterSource would be better from readability point of view and you just call that method inside the map method