Sobes.tech
Junior — Senior

Converting Stream to Set and List: Differences and Nuances

livecode

Task condition

There is a stream of objects of type A, to which operations .map(...) and .filter(...) are applied, and then the result is collected into different collections. It is necessary to explain the differences between Collectors.toSet() and Collectors.toList(): in which cases it is preferable to use each of them and what are the consequences of calling collect() again on the same Stream.

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

Set<A> set = s.collect(Collectors.toSet());
List<A> list = s.collect(Collectors.toList());