gpt4 book ai didi

Java + Postgresql : How to store Parent and List of all children in a HashMap>

转载 作者:行者123 更新时间:2023-11-30 01:43:16 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com