2017-05-22 2 views
-2
final List<Toy> toys = Arrays.asList("new Toy(1)", "new Toy(2)"); 

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     return Item.from(toy); //Creates Item type 
    }).collect(Collectors.toList); 

上記のコードでは、罰金を課し、Toysのリストから項目のリストを作成します。私が何をしたいか複数の要素にマップして収集する方法

はこのようなものです:

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     Item item1 = Item.from(toy); 
     Item item2 = Item.fromOther(toy); 

     List<Item> newItems = Arrays.asList(item1, item2); 
     return newItems; 
    }).collect(Collectors.toList); 

OR

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     return Item item1 = Item.from(toy); 
     return Item item2 = Item.fromOther(toy); //Two returns don't make sense but just want to illustrate the idea.  
    }).collect(Collectors.toList); 

だから、最初のコードにこれを比較し、最初のアプローチは、すべての玩具・オブジェクトの1つの項目オブジェクトを返します。

どのようにしてすべてのおもちゃに2つのアイテムオブジェクトを返すことができるのですか?

--UPDATE--

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     Item item1 = Item.from(toy); 
     Item item2 = Item.fromOther(toy); 

     return Arrays.asList(item1,item2); 
    }).collect(ArrayList<Item>::new, ArrayList::addAll,ArrayList::addAll); 
+0

あなたは解決策を発見した場合は、とあなたの質問を更新しません溶液。代わりに、関連する回答を受け入れます。 – VGR

+0

私は解決策を見つけられません – bob9123

+0

@ bob9123更新された投稿はあまり言わない。 'BasicRule'とは何ですか?どのようにマップしますか、なぜそれを明示的に提供する必要がありますか?最小限の実行可能な例が役に立ちます – Eugene

答えて

4

あなたはすでにあなただけflatMap

final List<Item> itemList = toys.stream() 
.map(toy -> Arrays.asList(Item.from(toy),Item.fromOther(toy)) 
.flatMap(List::stream) 
.collect(Collectors.toList()); 

または示唆されているように、あなたが完全にマッピングをドロップする必要がある...ということをやっている:

final List<Item> itemList = toys.stream() 
.flatMap(toy -> Stream.of(Item.from(toy),Item.fromOther(toy)))) 
.collect(Collectors.toList()); 
1

おもちゃごとに2つのアイテムを返す場合は、出力タイプはList<List<Item>>

List<List<Item>> itemList = 
    toys.stream() 
     .map(toy -> Arrays.asList(Item.from(toy),Item.fromOther(toy))) 
     .collect(Collectors.toList); 

あなたがflatMapを使用し、同じList<Item>に収集することがToyごとに2つのItem Sを希望する場合:

List<Item> itemList = 
    toys.stream() 
     .flatMap(toy -> Stream.of(Item.from(toy),Item.fromOther(toy))) 
     .collect(Collectors.toList); 
+0

2つの要素を含むリストを1つ持ちますが、 – bob9123

+0

@ bob9123この場合、 'map'の代わりに' flatMap'を使うべきです。編集を参照してください。 – Eran

関連する問題