How to map to multiple elements and collect

Viewed 6865
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);

This above codes work fines and will make a list of Items from the list of Toys.

What I want to do is something like this:

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

So comparing this to the first code, the first approach returns 1 Item object for every Toy Object.

How do i make it so I can return a two Item Objects for every Toy?

--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);
2 Answers
Related