Reputation: 393
I do not want create new list from Stream.collect method in second time. It should add in previous list only. I am trying to do like below but it is not working. As per document, Collectors.toList() is always create new list, and collect() method is not allowing old list. Is there any way i can reuse my previous list(listA) in second time.
List<A> listA = xList.stream().map().collect(Collectors.toList());
yList.stream().map().collect(**listA**);
Upvotes: 1
Views: 111
Reputation: 2678
You can do something like this -
List<A> listA = xList.stream().map().collect(Collectors.toList());
yList.stream().map().collect(Collectors.toCollection(() -> listA));
EDIT :
collect
method takes a Collector
and internally Collectors.toCollection
adds yList element to the original list as -
Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
return new CollectorImpl<>(collectionFactory, Collection<T>::add,
(r1, r2) -> { r1.addAll(r2); return r1; },
CH_ID);
}
Upvotes: 1
Reputation: 40024
There are several ways to accomplish it. Here are two. They are very similar.
List<A> list = Stream.of(xList, yList).flatMap(List::stream)
.map(<someFnc>)
.collect(Collectors.toList());
List<A> list2 = Stream.concat(xList.stream().map(<someFnc>),
yList.stream().map(<someFnc>)
.collect(Collectors.toList());
Upvotes: 3
Reputation: 89179
You can use Stream.concat
.
List<A> listA = Stream.concat(xList.stream().map(), yList.stream().map())
.collect(Collectors.toList());
Upvotes: 1
Reputation: 198023
Instead of using .collect
, write .forEach(listA::add)
.
(Technically, you should also replace Collectors.toList()
in the first example with Collectors.toCollection(ArrayList::new)
, because toList()
does not guarantee that it returns a mutable list.)
Upvotes: 3