A Java collection of value pairs? (tuples?)
Key-value pairs in Java can conveniently be handled using AbstractMap.SimpleEntry:
Alternatively, using Map.entry comes in handy:
Dealing with multi-value tuples? Try Apache Commons Lang:
These efficient techniques enable you to curate related data items without the need for custom classes.
Java 16 and records
As of Java 16, records offer an elegant way to create data containers:
Records provide immutable data carriers equipped with accessors and deconstruction patterns. It's as compact as it gets!
Custom tuple list for organized storage
For organized storage and order maintenance, create a custom TupleList class:
Efficient handling of primitive types
Eclipse Collections offers efficient primitive pair classes which significantly reduce autoboxing overhead:
Pair creation with ease
Static factory methods
Cheer up because Lombok and Android's Pair bring to you the static constructors:
These methods deliver null safety with less verbosity.
Safeguard your pairs
Ensure immutability of pairs when designing your Pair class for safe sharing across the codebase:
Don't forget to implement hashCode and equals to use Pairs in hash-based collections.
More tricks up your sleeve
The Power of "of" methods
Subclass ArrayList to add pairs using a custom "of" method:
Adding pairs now feels like a breeze:
Immutable entries
Jump on the Java 9 bandwagon. Creating immutable pairs has never been easier:
Use this in modern Java for trustable and read-only data.
Comparing pairs
Need to sort your pairs? Make your Pair class implement Comparable:
This lets you sort collections of pairs depending on key-value semantics.
Was this article helpful?