示例:一个查询抛出下一个结果集:
名称 |年龄 |总计
- 约翰·史密斯,45 岁,1000 岁
- 约翰·史密斯,56, 800
- 约翰·史密瑟斯,34 岁,500 岁
- 约翰·史密斯,56, 500
- 约翰·史密斯,56 岁,1100 岁
我想将此数组列表分成三个,并将它们存储在 HashMap 中,其中键是客户端名称。
我在想类似的事情
Arraylist<Row> rows = dao.getClientActivity();
Map map = new HashMap<Clients Name, Clients Row>();
Arraylist<Row> = null;
for (Row row : rows){
if (map.get(row.clientName) == null) list = new ArrayList<Row>();
list.add(row);
if(map.get(row.clientName) == null) map.put(row.clientName, list);
}
列表将始终按名称排序。
将上面的代码片段作为伪代码,我家里没有编码程序,我只是想到了这一点,我想我这个星期五测试了类似的东西,但它只打印在行上;
我不知道是否有更好的方法来做到这一点,但这是我想到的第一件事。
最佳答案
您的 map 声明应如下所示(假设 Row.clientName
为 String
):
Map<String, List<Row>> map = new HashMap<String, List<Row>>();
for 循环应如下所示:
for (Row row : rows){
/*Get the list of rows for current client name.*/
List<Row> currRows = map.get(row.clientName);
if (currRows == null) {/*If not list exists for*/
currRows = new ArrayList<Row>(); /*create a new one*/
map.put(row.clientName, currRows); /*and put it in the map*/
}
currRows.add(row);/*add the current row to the list*/
}
关于java - 如何将一个大数组列表分解为 HashMap 中的多个数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059436/