Sobes.tech
Junior — Senior

Reusing Stream API for collecting into different structures

livecode

Task condition

There is a stream Stream<A> stream, to which .map(...) and .filter(...) operations are sequentially applied. You need to perform two different result collections:

  • the first into a Set<A>;
  • the second into a List<A>.

Why might attempting to call the second collect(...) lead to an error? Rewrite the code so that both collections are possible.

Stream<A> stream = ...map(...).filter(...);

Set<A> resultSet = stream.collect(Collectors.toSet());
List<A> resultList = stream.collect(Collectors.toList());