Java将ArrayList映射到HashMap
我给了page一个ArrayList,其中每个文档都有一个名为type的属性 我不知道唯一类型或文档的数量 我想把这个ArrayList排序成一个HashMap,但是我在想它时遇到了一些麻烦 一些伪代码希望Java将ArrayList映射到HashMap,java,sorting,arraylist,hashmap,Java,Sorting,Arraylist,Hashmap,我给了page一个ArrayList,其中每个文档都有一个名为type的属性 我不知道唯一类型或文档的数量 我想把这个ArrayList排序成一个HashMap,但是我在想它时遇到了一些麻烦 一些伪代码希望 for (int i = 0; i < documents.size(); i++) { if there is an array for documents[i].type add to this array else create a new array for
for (int i = 0; i < documents.size(); i++)
{
if there is an array for documents[i].type
add to this array
else create a new array for this type
add document[i].type and the array of documents with matching type to the hashmap
}
for(int i=0;i
我知道这是错误的方法,显然是行不通的。我愿意接受任何建议
谢谢//创建用于存储内容的映射,注意我使用的是列表而不是数组
// create the map to store stuff, note I'm using a List instead of an array
// in my opinion it's a bit cleaner
Map<String, List<Document>> map = new HashMap<String, List<Document>>();
// now iterate through each document
for(Document d : documents){
// check to see if this type is already known
List<Document> list = map.get(d.type);
if(list == null){
// list is null when it wasn't found in the map
// this is a new type, create a new list
list = new ArrayList<Document>();
// store the list in the map
map.put(d.type, list);
}
// finally, whether we got a hit or a miss, we want
// to add this document to the list for this type
list.add(d);
}
//在我看来,这有点干净
Map Map=newhashmap();
//现在遍历每个文档
用于(文件d:文件){
//检查此类型是否已知
List=map.get(d.type);
if(list==null){
//列表在映射中未找到时为空
//这是一个新类型,请创建一个新列表
列表=新的ArrayList();
//将列表存储在地图中
地图放置(d.类型,列表);
}
//最后,无论我们成功还是失败,我们都希望
//将此文档添加到此类型的列表中
列表.添加(d);
}
我认为您要查找的术语不是按类型排序,而是按类型索引。”s接口设计用于将键映射到多个值,而无需处理值集合。特别是,番石榴有一种方法,可以完全按照你的意图来做:
List<Document> documents = ...
ImmutableListMultimap<Type, Document> typeIndex = Multimaps.index(documents,
new Function<Document, Type>() {
public Type apply(Document input) {
return input.getType();
}
});
for(Type type : typeIndex.keySet()) {
ImmutableList<Document> documentsWithType = typeIndex.get(type);
...
}
列出文档=。。。
ImmutableListMultimap类型索引=Multimaps.index(文档,
新函数(){
公共类型应用(文档输入){
返回input.getType();
}
});
for(类型:typeIndex.keySet()){
ImmutableList documentsWithType=typeIndex.get(类型);
...
}
这与执行以下操作基本相同:
ListMultimap<Type, Document> typeIndex = ArrayListMultimap.create();
for(Document document : documents) {
typeIndex.put(document.getType(), document);
}
ListMultimap typeIndex=ArrayListMultimap.create();
用于(文档:文档){
typeIndex.put(document.getType(),document);
}
除了生成的多重映射是不可变的之外。还要注意的是,上述内容几乎完全等同于Mark的示例