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
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With