2016-08-14 55 views
1

在我的一個需求中,我有一個關鍵字和與多個文檔對象關聯的每個關鍵字 這些我存儲在帶有鍵和值對的HashMap中.Key是id和值是 文檔列表與關鍵如何從集合對象中檢索用戶定義的對象

 Ex : HashMap<String,List<Document>> 

     I want to put all the list documents in one collection object , ie.List<Documents> (all documents of all keys) 
     When i am using values() method of Hashmap i am getting Collection<List<Document>> 

     If i want to get all the document objects i have to get each List<Document> ,iterate and add it into new collection object. 

     other than this Is there any best way i can get all the Documents one at a time in collection Object. 
     using any apache common-collections or apache commons-collections4 api ? 


     ArrayList<Document> al = new ArrayList<Document>(); 
     Document dto1 = new Document(); 
     dto1.setResearchId("1"); 
     dto1.setIsinCode("isinCode1"); 
     dto1.setEquity("equity1"); 

     Document dto2 = new Document(); 
     dto2.setResearchId("2"); 
     dto2.setIsinCode("isinCode2"); 
     dto2.setEquity("equity2"); 

     Document dto3 = new Document(); 
     dto3.setResearchId("3"); 
     dto3.setIsinCode("isinCode3"); 
     dto3.setEquity("equity3"); 

     Document dto4 = new Document(); 
     dto4.setResearchId("4"); 
     dto4.setIsinCode("isinCode4"); 
     dto4.setEquity("equity4"); 

     al.add(dto1); 
     al.add(dto2); 
     al.add(dto3); 
     al.add(dto4); 

     Map<String ,List<Document>> mapList = 
       new HashMap<String,List<Document>>(); 
     mapList.put("1", al); 
     mapList.put("2", al); 
     mapList.put("3", al); 


     Excepted output : Collection<Document> 

     For sample i have added the same arraylist object in to my Map 
     but in actual i will have different arrayList objects. 
+1

你能展示示例代碼嗎?跟隨你想要的會更容易。很高興看到你嘗試過的東西。 –

回答

1

好像你正試圖將中的的值平鋪到一個集合中。 Java的8允許你這樣做很容易:

List<Document> flatDocuments = // could also be defined as a Collection<Document> 
    mapList.values() 
      .stream() 
      .flatMap(Collection::stream) 
      .collect(Collectors.toList()); 

另外,如果你只想做他們的東西(如打印),你可以跳過收集階段,對它們進行操作,直接使用forEach

mapList.values() 
     .stream() 
     .flatMap(Collection::stream) 
     .forEach(System.out::println); 

編輯:
對於老的Java版本你必須自己使用循環(或者,當然,使用一些第三方會爲你)來實現相同的邏輯:

List<Document> flatDocuments = new LinkedList<>(); 
for (List<Document> list : mapList.values()) { 
    flatDocuments.addAll(list); 
} 
+0

我們使用的是JDK 7,而不是8 – Maddy

+0

@Maddy我強烈建議升級到Java 8.無論如何,在這種情況下,streams API只是一個很好的選擇,你可以通過迭代'values()來完成相同的行爲。 '集合。我已經編輯了我的答案,並說明了如何做到這一點。 – Mureinik

0

既然你是在暗示阿帕奇公地collections4自己相關的,你居然看的呢?

values()方法MultiValuedMap完全符合你的要求。

Collection<V> values()

獲取一個Collection視圖包含在該多值地圖的所有值的。

實現通常返回一個集合,其中包含來自所有鍵的值的組合。