user84
user84

Reputation: 393

Stream collect method

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

Answers (4)

Pankaj
Pankaj

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

WJS
WJS

Reputation: 40024

There are several ways to accomplish it. Here are two. They are very similar.

  • The first simply flattens the two lists supplied directly.
  • The second concatenates two streams together.
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

Unmitigated
Unmitigated

Reputation: 89179

You can use Stream.concat.

List<A> listA = Stream.concat(xList.stream().map(), yList.stream().map())
    .collect(Collectors.toList());

Upvotes: 1

Louis Wasserman
Louis Wasserman

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

Related Questions