2010-09-27 120 views
2

我有頁獲得ArrayList <文檔>其中每個文檔都有一個稱爲類型的屬性。Java將ArrayList映射到HashMap

我不知道唯一類型或文檔的數量。

我想將這個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 this type 
    add document[i].type and the array of documents with matching type to the hashmap 
} 

我知道這是錯誤的做法,明確將無法正常工作。我願意接受任何建議。

謝謝

回答

8
// 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); 
} 
+0

+1用於添加有用的評論 – Ibrahim 2010-09-28 00:16:29

2

我想,而不是排序的類型,你要找的術語是索引的類型。 GuavaMultimap接口設計用於將鍵映射到多個值,而沒有處理值集合的麻煩。特別是,番石榴具有它的設計做的正是一種方法你想要做什麼:

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); 
    ... 
} 

這是幾乎一樣的做:

ListMultimap<Type, Document> typeIndex = ArrayListMultimap.create(); 
for(Document document : documents) { 
    typeIndex.put(document.getType(), document); 
} 

只是將得到多重映射是不可變的。還要注意,以上幾乎完全等同於馬克的例子。