Turning a list into a map keyed by id is the standard way to avoid repeated linear searches later.
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());
Topic[id=2, title=Maps]
ids = [1, 2, 3]
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