There is an another variant of collect method provided by LongStream class and
similarly by IntStream and DoubleStream classes too .
<R> R collect(Supplier<R> supplier,
ObjLongConsumer<R> accumulator,
BiConsumer<R,R> combiner)
Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result. This produces a result equivalent to:
R result = supplier.get();
for (long element : this stream)
accumulator.accept(result, element);
return result;
Like reduce(long, LongBinaryOperator), collect operations can be parallelized without requiring additional synchronization.
This is a terminal operation.
And answer to your question with this collect method is as below :
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, (list, value) -> list.add(value)
, (list1, list2) -> list1.addAll(list2));
Below is the method reference variant which is quite smart but some what tricky to understand :
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, List::add , List::addAll);
Below will be the HashSet variant :
LongStream.of(1L, 2L, 3L, 3).filter(i -> i > 2)
.collect(HashSet::new, HashSet::add, HashSet::addAll);
Similarly LinkedList variant is like this :
LongStream.of(1L, 2L, 3L, 3L)
.filter(i -> i > 2)
.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
sourceLongList
afterwards there’sCollection.removeIf(…)
for convenience. – CryptographyList<Long> targetLongList = sourceLongList.stream().collect(Collectors.toList());
– Landy