toMap projects each element into a key/value pair; a merge function resolves clashes.
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'));
banana
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