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
  • 387,369
  • 54
  • 702
  • 768
MuchaZ
  • 391
  • 4
  • 18
  • 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

30

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
  • 387,369
  • 54
  • 702
  • 768
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
  • 422
  • 3
  • 6