Mic*_*yle 2 java sorting arraylist hashmap
我给页面获取了一个ArrayList <Document>,其中每个文档都有一个名为type的属性.
我不知道唯一类型或文档的数量.
我想将这个ArrayList排序为HashMap <type,document []>但是我在解决它时遇到了一些麻烦.
有些伪代码会喜欢
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
}
Run Code Online (Sandbox Code Playgroud)
我知道这是错误的做法,显然不会奏效.我对任何建议持开放态度.
谢谢
// 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);
}
Run Code Online (Sandbox Code Playgroud)