Java + Postgresql : How to store Parent and List of all children in a HashMap<String, ArrayList <字符串>>

标签 java sql database postgresql hashmap

我有一个 sql 表 Children :

| ParentName | ChildrenName |
 ———————————————————————————
| parent 1   | child 1      |
| parent 1   | child 2      |
| parent 2   | child 3      |
| parent 1   | child 4      |
| ...        | ....         |

我的目标是构造一个java HashMap<String , ArrayList<String>>包含 ParentName 作为键和 ChildrenName 列表作为值。

我应该使用sql查询来执行处理吗?或者选择所有数据并通过java处理它?<​​/p>

最佳答案

关于你的第二个选择:
通过简单的查询从数据库获取所有数据并在 Java 中映射数据

你可以这样做(阅读代码注释):

public static void main(String[] args) {
    // provide a query as String
    String query = "SELECT ParentName, ChildName FROM some_table";
    // provide the data structure
    Map<String, List<String>> results = new HashMap<>();
    // connect to your database
    Connection connection; // this has to be created using a suitable JDBC implementation

    try (PreparedStatement ps = connection.prepareStatement(query)) {
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            String parentName = rs.getString(1);
            String childName = rs.getString(2);

            // add them to the map
            if (results.containsKey(parentName)) {
                /* 
                 * if the key already exists in the map, 
                 * just add the current name to its value(s)
                 */
                results.get(parentName).add(childName);
            } else {
                // create a new list as the value for the new key
                List<String> childNames = new ArrayList<>();
                // add the current child name to it
                childNames.add(childName);
                // and put the new key and value in the map
                results.put(parentName, childNames);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // print the results
    results.forEach((p, c) -> System.out.println(p + ": " + String.join(", ", c)));
}

关于Java + Postgresql : How to store Parent and List of all children in a HashMap<String, ArrayList <字符串>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191605/

相关文章:

java - 最好使用 Maven 程序集插件创建 zip 原型(prototype)(从project.basedir 或project.build.directory 开始)?

java - 一个字符的字符串可以转换为字符吗?

java - 在 IntelliJ 中执行程序/编译时出错,命令行中没有错误

mysql - 如何在 MySQL 中为表和该表的列创建同义词?

php - 如何将存在于 2 台不同机器上的 2 个数据库相互连接

windows-xp - JDK 问题 - 无法加载类文件

Mysql根据不同表的日期时间过滤数据

SQL Server - 有没有一种简单的方法可以在搜索时忽略引号?

database - 用 cocoa 创建数据库软件

php - 警告 : mysql_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known