【问题标题】:How to get data as a Map<String, List<String>> using a single query?如何使用单个查询将数据作为 Map<String, List<String>> 获取?
【发布时间】:2021-12-25 22:42:38
【问题描述】:

如何使用单个查询以Map&lt;String, List&lt;String&gt;&gt; 的形式获取数据?
我有表过滤器:

|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  |

所以,我需要像键一样获得 keyword,像值列表一样获得 filter_code。 收入数据:idkeyword 编辑:在输出中,我需要得到Map&lt;keyword, List&lt;filter_code&gt;&gt;。所有参数都是字符串

【问题讨论】:

  • 请添加预期输出以更好地解释您要查找的内容。

标签: java sql postgresql hibernate collections


【解决方案1】:

试试这个。

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);
}

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-04-01
    相关资源
    最近更新 更多