Java streams 32. Collect 8. Collectors.toConcurrentMap()

Creating Map object using Collectors.toConcurrentMap() collector

    ConcurrentMap<String, Integer> map1 = 
Stream.of("cat", "fish", "dog")
.parallel()
.collect(Collectors.toConcurrentMap(Function.identity(),
String::length));
System.out.print(map1); //prints: {fish=4, cat=3, dog=3}
try {
ConcurrentMap<String, Integer> map2 =
Stream.of("cat", "fish", "cat")
.parallel()
.collect(Collectors.toConcurrentMap(Function.identity(),
String::length));
} catch (Exception ex){
System.out.print(ex.getMessage());
//prints: Duplicate key cat (attempted merging values 3 and 3)
}
//First key wins
ConcurrentMap<String, Integer> map3 =
Stream.of("cat", "fish", "cat")
.parallel()
.collect(Collectors
.toConcurrentMap(Function.identity(),
String::length,
(oldValue, nextValue) -> oldValue));
System.out.print(map3); //prints: {fish=4, cat=3}
//Combines the values
ConcurrentMap<String, Integer> map4 =
Stream.of("cat", "fish", "cat")
.parallel()
.collect(Collectors
.toConcurrentMap(Function.identity(),
String::length,
(oldValue, nextValue) -> oldValue + 100));
System.out.print(map4); //prints: {fish=4, cat=103}
ConcurrentSkipListMap<String, Integer> map6 =
Stream.of("cat", "fish", "cat", "cat")
.parallel()
.collect(Collectors
.toConcurrentMap(Function.identity(),
String::length,
(oldValue, nextValue) -> oldValue + 100,
ConcurrentSkipListMap::new));
System.out.print(map6); //prints: {cat=203, fish=4}

--

--

--

Born in Moscow, lived in Crimea, now lives in the US. Used to be physicist and rock climber, now programmer and writer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Riding Rails

YouTube System Design — Video Upload Service Architecture | Newsletter

Day 11: Coroutines With Unity

Nuxeo Unauthenticated RCE analysis

Helm — K8S Package Manager

Beginner’s guide to self-hosting on the internet with SSH tunnel and free domain name

Homeserver hosting nextcloud connecting to Cloud VPC via SSH tunnel and proxying requests from clients using Caddy.

CS371p Spring 2022: Vincent Huynh

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nick Samoylov

Nick Samoylov

Born in Moscow, lived in Crimea, now lives in the US. Used to be physicist and rock climber, now programmer and writer.

More from Medium

Data type and Decision making Java

Packages, Comments, and Variables

import Json dependency in JAVA

Types of variables in Java