This question already has answers here:
Collection to stream to a new collection

(4个答案)


4年前关闭。




我有以下代码:
Queue<Reward> possibleRewards =
    Stream.of(Reward.values())
          .flatMap(reward -> IntStream.range(0, reward.getOccurencies()).mapToObj(i -> reward))
          .collect(Collectors.toList());

如您所见,我需要将Stream的元素收集到Queue而不是List中。但是,没有Collectors.toQueue()方法。如何将元素收集到Queue中?

最佳答案

您可以使用Collectors.toCollection(),它使您可以选择想要生成的任何Collection实现:

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

10-01 18:09