Records can be declared inside a method, which is the tidy way to carry an intermediate pair through a stream without a throwaway top-level class.
var words = List.of("java", "sql", "hibernate", "kafka");
record Scored(String word, int length) {}
List<String> report = words.stream()
.map(w -> new Scored(w, w.length()))
.sorted(Comparator.comparingInt(Scored::length).reversed())
.map(s -> s.word() + "(" + s.length() + ")")
.toList();
System.out.println(report);
[hibernate(9), kafka(5), java(4), sql(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