How to get data as a Map<String, List<String>> using a single query?

Viewed 267

How to get data as a Map<String, List<String>> using a single query?
I have table filters:

|id|filter_name|filter_code| keyword|
------------------------------------
|1 |  banana   |    237    |category|
|2 |   apple   |    250    |category|
|3 |   water   |    320    |category|
|4 |   owner   |    4410   | param  |
|5 |   place   |    5389   | param  |

So, I need to get keyword like a key and filter_code like a list of values. Income data: id and keyword Edited: In the output, I need to get Map<keyword, List<filter_code>>. All params are strings

1 Answers

Try this.

static Map<String, List<String>> read() throws SQLException {
    try (Connection con = DriverManager.getConnection(CONSTR);
        PreparedStatement stat = con.prepareStatement(
            "select keyword, filter_code from filters");
        ResultSet rs = stat.executeQuery()) {
        Map<String, List<String>> map = new LinkedHashMap<>();
        while (rs.next())
            map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>())
                .add(rs.getString(2));
        return map;
    }
}

public static void main(String[] args) throws SQLException {
    Map<String, List<String>> map = read();
    System.out.println(map);
}

output:

{category=[237, 250, 320], param=[4410, 5389]}
Related