Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect the elements of a Stream into a Queue? [duplicate]

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?

like image 466
MuchaZ Avatar asked Nov 30 '16 11:11

MuchaZ


People also ask

What is the function used to duplicate a stream?

CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

How does stream detect duplicate values in a List?

Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.

How do I get unique values from a collection stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

How do I find duplicate values in Java 8?

In Java 8 Stream, filter with Set. Add() is the fastest algorithm to find duplicate elements, because it loops only one time. Set<T> items = new HashSet<>(); return list.


1 Answers

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
like image 142
Eran Avatar answered Oct 05 '22 22:10

Eran