我是 Java 的新手,我很难解决这个问题。
假设我有两个数组列表 personIdList
和 titlelist
,它们在 ResultSet 对象迭代的帮助下由数据库填充。
personIdList.add(repPersonId.getLong("personID"));
titelList.add(repTitel.getString("titel"));
第一个 Arraylist(personIdList
) 包含来自不同 Composer 的 ID,如下所示:
[34, 34, 34, 37, 38, 133, 232, 232, 285, 285, 285, 285]
第二个 List(titlelist
) 包含来自该 Composer 的标题,如下所示:
[Symphonie, Sinfonia Concertante, Oper, Symphonie, Ouverture zur Oper, Ouverture zur Oper, Konzert für zwei Klaviere, Sinfonie, Chöre aus der Schauspielmusik, Requiem, Klavierkonzert, Klavierkonzert]
我能以某种方式在这些数组之间建立连接吗?因为 composer id 应该连接到相应的 Title。
例如(伪代码):personIdList.get(34) 应该给我所有与 Id 34 相关的标题。
我必须使用 ArrayLists 还是已经有可以做到这一点的东西?
最佳答案
正如RC所说。如果你不打算 ORM 映射它,你可以迭代 id 列表并创建一个新的 Map(键值对集合):
Map<Integer, List<String> personTitles = new HashMap<>();
for(Integer id: personIdList) {
// your solution for retrieving the titles from the database
// i would imagine you're using an entityManager.query or something which returns the result set of the titles
// where you have to pass the `id` as a parameter
// and get the list of titles and store them in a List<String>
personTitles.put(id, `your retrieved List<String>`);
}
然后你可以说 personTitles.get(32)
应该检索你的标题列表。
如果您可以发布更多关于如何从数据库中检索条目的代码,那将会很有帮助。
关于java - 将两个 ArrayList 相互连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45392541/