Maps: group records into a lookup index with toMap

Turning a list into a map keyed by id is the standard way to avoid repeated linear searches later.

Code
record Topic(int id, String title) {}
var topics = List.of(new Topic(1, "Streams"), new Topic(2, "Maps"), new Topic(3, "Collections"));

Map<Integer, Topic> byId = topics.stream()
        .collect(Collectors.toMap(Topic::id, Function.identity(), (a, b) -> a, TreeMap::new));

System.out.println(byId.get(2));
System.out.println("ids = " + byId.keySet());
Output
Topic[id=2, title=Maps]
ids = [1, 2, 3]
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-30