10

I have the following code:

Queue<Reward> possibleRewards = 
    Stream.of(Reward.values())
          .flatMap(reward -> IntStream.range(0, reward.getOccurencies()).mapToObj(i -> reward))
          .collect(Collectors.toList());

As you can see, I need to collect the elements of the Stream into a Queue, not a List. However, there's no Collectors.toQueue() method. How can I collect the elements into a Queue?

Eran
  • 374,785
  • 51
  • 663
  • 734
MuchaZ
  • 381
  • 4
  • 17
  • 2
    What stops you from instantiating the queue from the resulting list anyway? See http://stackoverflow.com/questions/20708358/convert-from-queue-to-arraylist – dabadaba Nov 30 '16 at 11:13
  • 2
    http://stackoverflow.com/questions/21522341/collection-to-stream-to-a-new-collection – Tunaki Nov 30 '16 at 11:18

2 Answers2

27

You can use Collectors.toCollection(), which lets you choose whatever Collection implementation you wish to produce:

Queue<Reward> possibleRewards = 
    Stream.of(Reward.values())
          .flatMap(reward -> IntStream.range(0, reward.getOccurencies()).mapToObj(i -> reward))
          .collect(Collectors.toCollection(PriorityQueue::new)); // use whatever Queue 
                                                                 // implementation you want
Eran
  • 374,785
  • 51
  • 663
  • 734
1
Queue<Reward> possibleRewards = new LinkedBlockingQueue<>(); //Or whichever type of queue you would like
possibleRewards.addAll(Stream.of(Reward.values())
    .flatMap(reward -> IntStream.range(0, reward.getOccurencies()).mapToObj(i -> reward))
    .collect(Collectors.toList()));
AleSod
  • 402
  • 3
  • 6