有没有什么办法可以在 java 中对相似的数据进行分组?
我想将所有具有相同 id 的数据分组并打印出来。
我正在使用 jdbc 查询数据并正在搜索我可以为此使用的库。
有什么想法吗? 谢谢
最佳答案
使用 Map<GroupID, List<Data>>
.
Map<Long, List<Data>> groups = new HashMap<Long, List<Data>>();
while (resultSet.next()) {
Long groupId = resultSet.getLong("groupId");
String col1 = resultSet.getString("col1");
String col2 = resultSet.getString("col2");
// ...
List<Data> group = groups.get(groupId);
if (group == null) {
group = new ArrayList<Data>();
groups.put(groupId, group);
}
group.add(new Data(groupId, col1, col2 /* ... */));
}
您也可以将其设为另一个(父)bean 的属性。
另见:
关于java - 在java中分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3494608/