Quick revision
The short answer
We recommend replacing nested Pair types with small named records, such as record OrderLine(long productId, BigDecimal price), so the code documents its own data. Records generate equals() and hashCode() from all components, which makes a record like record CountryCity(String country, String city) a correct composite map key and a clean grouping key for Collectors.groupingBy, as long as its components are immutable.
What to remember
In this answer, we saw that nested pairs compile but hide meaning, and that named records fix this for a few lines of code. Records generate equals() and hashCode() from all components, so they are correct composite map keys and clear grouping keys for Collectors.groupingBy, replacing fragile concatenated strings. Compact constructors validate and normalise components, and List.copyOf keeps list components immutable so keys never change. A generic Pair stays only in truly generic utilities.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We recommend replacing nested Pair types with small named records, such as record OrderLine(long productId, BigDecimal price), so the code documents its own data. Records generate equals() and hashCode() from all components, which makes a record like record CountryCity(String country, String city) a correct composite map key and a clean grouping key for Collectors.groupingBy, as long as its components are immutable.
Why this question is asked
Generic pairs creep into codebases one convenient shortcut at a time, and after a year we find signatures that nobody can read without a debugger. Interviewers use this scenario to see how a senior engineer reviews code: not just spotting the smell, but proposing a replacement that is cheaper to maintain, and knowing the traps of the replacement. In this answer, we will look at what the nested pairs really cost, rewrite them as records, see why records make good map keys and grouping keys, validate them with compact constructors, and finish with the one place where a generic Pair is still fine.
1What the Nested Pairs Are Hiding
Let us read the signature from the review as a newcomer would.
Every getLeft() and getRight() is a small puzzle. The reader has to open the method to learn that the inner pair is a customer name and a loyalty level, and that the list holds product ids with prices. The types are correct, so the compiler is happy, but the meaning lives only in the author's head. Worse, swapping two values of the same type, such as two Strings, compiles and fails silently.
The maps keyed by Pair<String, String> have the same problem. A key of ("FR", "Paris") does not say which part is the country. And if Pair comes from a library, its equals() and hashCode() behave correctly, but we now depend on that library's choices for one of our most important data structures.
2Replacing Pairs With Named Records
A record is a class that only carries data. We declare the components and the compiler writes the constructor, accessors, equals(), hashCode() and toString(). So the fix costs a few lines and gives each value a name.
The call sites now read like the business language. Notice also that toString() prints the component names, so logs and test failures become readable for free. In a review we would suggest doing this change gradually: introduce the records, change one method at a time, and let the compiler point at every caller that needs updating.
3Records as Composite Map Keys
A composite key is a key made of several fields, such as a country and a city. A map key must have an equals() and hashCode() that agree: equal keys must give the same hash code. Records generate both from all their components, so a record is a correct key without any hand-written code.
| Key style | Example | Problem |
|---|---|---|
| Concatenated String | "FR|Paris" | breaks if a value contains |, no types |
Pair<String, String> | Pair.of("FR", "Paris") | which side is the country? |
record CountryCity | new CountryCity("FR", "Paris") | none, if components are immutable |
The condition is that the components must be immutable. HashMap stores each entry in a bucket chosen from the key's hash code at the moment of put(). If the key changes afterwards, its hash code changes, and the map looks in the wrong bucket. Strings, numbers, enums and other records are safe components. A List is not, unless we make it immutable.
4Grouping by Several Fields
The same idea cleans up grouping. Without records, people group by a concatenated string such as country + "|" + city, which breaks the moment a city name contains the separator and forces the reader to split strings later. With a record, the grouping key is typed and named.
5Validating Keys With a Compact Constructor
A compact constructor is a record constructor without a parameter list. It runs before the fields are assigned, and it can check or change the parameters. We use it to make keys safe: reject nulls, trim spaces and normalise case, so "fr " and "FR" become the same key. For a list component, we take an immutable copy, which also fixes the follow-up problem below.
Finally, a generic Pair still has a place in truly generic code, where the two values really have no domain meaning, for example a utility that zips two streams into pairs. Everywhere else, the review comment is the same: give it a name.
6Follow-up questions
What goes wrong if a record component is a mutable list used in a map key?
The record's hashCode() is computed from the list's current contents. If someone adds an element to the list after the record was put into a HashMap, the hash code changes, so get() looks in a different bucket and returns null even though the entry is still there. The entry also cannot be removed by key, so it leaks. The fix is to copy the list with List.copyOf in the compact constructor, which makes the component immutable.
Is a record faster than a Pair?
Usually about the same. Both are small objects with two fields. The benefit of a record is readability and correctness, not speed. Records also cannot be subclassed, which makes them simple for the JVM and for readers.
Can records replace JPA entities as well?
No. JPA entities need a no-argument constructor, mutable state and usually proxies, and records are final and immutable. Records are a good fit for DTOs, query projections, value objects and keys, but not for the entities themselves.
7Conclusion
In this answer, we saw that nested pairs compile but hide meaning, and that named records fix this for a few lines of code. Records generate equals() and hashCode() from all components, so they are correct composite map keys and clear grouping keys for Collectors.groupingBy, replacing fragile concatenated strings. Compact constructors validate and normalise components, and List.copyOf keeps list components immutable so keys never change. A generic Pair stays only in truly generic utilities.
Open with
In the review, I would say the types are correct but unreadable. Pair of Pair of String and Integer, plus a list of Pair of Long and BigDecimal, forces every reader to open the method to learn what left and right mean, and swapping two values of the same type compiles silently.
Then, if they want more
I would replace them with named records, for example record Customer(String name, int loyaltyLevel), record OrderLine(long productId, BigDecimal price), and an OrderSummary that holds both. Call sites then read order.customer().name(), and toString prints the field names in logs. For the maps keyed by Pair of String and String, I would use a record such as CountryCity.
A record's equals and hashCode are generated from all components, so it is a correct composite key, provided the components are immutable. The same record replaces concatenated keys like country plus a pipe plus city in Collectors.groupingBy, which break when a value contains the separator.
I would add a compact constructor to reject nulls and normalise values, trimming and upper-casing the country with Locale.ROOT, so equal business keys really are equal. If a component is a list, I copy it with List.copyOf, because a mutable list in a key changes the hash code and loses the entry.
I would keep a generic Pair only in truly generic code, such as a zip utility.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "In a code review you find methods returning Pair<Pair<String, Integer>, List<Pair<Long...": https://scrivio-interview-library.netlify.app/java/collections-overview/ef601584ab/