Java: Build a Map with Collectors.toMap

toMap projects each element into a key/value pair; a merge function resolves clashes.

Code
List<String> words = List.of("apple", "banana", "cherry");
Map<Character, String> byInitial = words.stream()
        .collect(Collectors.toMap(w -> w.charAt(0), w -> w));
System.out.println(byInitial.get('b'));
Output
banana
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26