You can use both toConcurrentMap for serial stream and toMap for parallel stream. The difference is
toConcurrentMap() usually faster for a parallel thread than for a serial threadtoMap() usually faster for a serial stream than for a parallel stream
If you donβt know where your thread came from and want to do it faster in both cases, you can write like this:
Map<String, String> niMap = niStream.collect( niStream.isParallel() ? Collectors.toConcurrentMap(NameId::getName, NameId::getId) : Collectors.toMap(NameId::getName, NameId::getId) );
The difference is that toConcurrentMap() is a CONCURRENT collector, which means that it uses a parallel data structure ( ConcurrentHashMap in the current implementation), which can be populated simultaneously from different threads. For a serial stream, this adds some unnecessary overhead, but for a parallel stream it is faster than using toMap() , as in the case of toMap() , separate non-competitive Map instances will be created for each parallel stream, then these Maps are combined, which is not very fast for large cards.
Please note that my StreamEx library, which extends the standard Stream API, adds toMap() , which uses parallel assembly for parallel flow and non-competitive collection for sequential:
Map<String, String> niMap = StreamEx.of(niStream) .toMap(NameId::getName, NameId::getId);
source share