2016-08-14 17 views
1

私の必要条件の1つに、キーと複数のドキュメントオブジェクトに関連付けられた各キーがあります これらは、キーと値のペアを持つHas​​hMapに格納されています。値は、あなたがApacheのコモンズ-collections4自分をそのキーコレクションのコレクションからユーザー定義オブジェクトを取得する方法

 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

あなたは、単一のコレクションにMapの値のList Sを平らにしようとしているように思えます。 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); 

EDIT:古いJavaのバージョンの
あなた自身がループを使用して(または、もちろん、あなたのためにそれをしない、いくつかのサードパーティ製を使用)と同じロジックを実装する必要があると思います:

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

私たちはJDK 7を使用していますが、8 – Maddy

+0

ではありません@Maddy Java 8にアップグレードすることを強くお勧めします。この場合、ストリームAPIはちょっとしたことですが、 'values() 'を反復して、コレクション。私はこれをどのように行うことができるかの例を使って答えを編集しました。 – Mureinik

0

に関連した 文書の一覧示唆しているされているためと、あなたが実際にそれを見たのですか?

values()MultiValuedMapの方法は、あなたが欲しいものを正確に行います。

Collection<V> values()

この多値マップに含まれるすべての値のCollectionビューを取得します。

実装は、通常、すべてのキーの値の組み合わせを含むコレクションを返します。

関連する問題