I am porting a .NET RESTful server (no UI) to Java 8. It looks like the best equivalent of Tuple (I use it a lot) is Map.entry. I don't see any downside to this, it's just a weird use of the class.
-
5I would refrain from using Map.Entry. At best, it'll be confusing. There's no harm in creating your own Tuple class. – Michael Bianconi Jun 30 '20 at 23:39
-
I agree with @MichaelBianconi. I find code using pair and tuple classes really difficult to read, as they don't tell you what's in them. – user207421 Jul 01 '20 at 01:44
2 Answers
It really isn't a good class to use.
There is nothing stopping you from creating your own Tuple<A,B>
class. But there is a reason why Java doesn't include one -- in general, types should have meaningful names. "Tuple" isn't really telling you what is in the tuple.
If you are using var nameAndAdress = new Tuple<>(name, address)
, you are relying on the name of the variable telling you what the tuple is. As soon as you assign this tuple to another variable, you lose that information. Even worse, you lose type safety, since you can assign any similar tuple to this variable. Creating an explicit NameAndAddress
class avoids this pitfall.
Yes, you might end up with a few more classes - but you actually get idiomatic Java code that other devs can readily use instead of trying to port foreign idioms to Java.
Abusing Map.Entry
is even worse, as a typical Java dev would not expect to see Map.Entry
outside of, you know, a map.
So, prefer meaningful types over a generic tuple class, and both of those over Map.Entry
.
As a side note: Records will likely help a lot in reducing boilerplate for creating such classes. Alternatively, use Lombok.

- 7,639
- 2
- 37
- 57
A route that may be helpful instead of trying to utilize the Map.Entry
class would be to use some common Java libraries that supply a Tuple
type. This is a good article outlining different libraries/approaches that are widely used in the Java community to supplement the absence of Tuples
. Examples are libraries like Apache Commons, which provides a mutable/immutable tuple, or Vavr which is a functional library that provides immutable tuples. I have used both of these previous libraries, and have found them to be very useful.

- 69
- 4