I'm looking for a KeyValuePair class in Java. Since java.util heavily uses interfaces there is no concrete implementation provided, only the Map.Entry interface.
Is there some canonical implementation I can import? It is one of those "plumbers programming" classes I hate to implement 100x times.
I'd recommend against using a generic KeyValuePair class. Much better to define a domain-specific class with more informative accessors (e.g. getProductId(), getProductPrice()). –
AdamskiJun 4 '10 at 10:04
12
@Adamski: I disagree. We don't use domain-specific Map or List classes, why should this be any different? A KeyValuePair is just a Map with one entry. –
skaffmanJun 4 '10 at 10:21
2
@skaffman: Fair point but I think the concept of a generic Pair is more easily open to abuse than passing Collections around. For example, if someone wants to return two values from a method it's tempting to return a Pair<X,Y> but typically this is indicative of an underlying design problem (e.g. Why aren't X and Y unified somehow anyway in the domain model if they're intrinsically related?) –
AdamskiJun 4 '10 at 10:31
7
@Adamski: Because it's not <X,Y>, it's <Key,Value>. He's not asking for an arbitrary Pair type, he's asking for a KeyValuePair type. –
skaffmanJun 4 '10 at 10:38
1
Despite this I would much rather pass around a single object instance in my code, potentially with a getKey() method defined; e.g. I prefer: processProduct(Product) to processProduct(KeyValuePair<Integer, Product>) where the Integer is the product ID. I agree that KeyValuePair (i.e. Map.Entry) or even a generic Pair is useful within a method logic but I don't like it to "leak out" as a return type or be supplied as a method parameter; e.g. I never pass around Map.Entry. –
AdamskiJun 4 '10 at 10:52
url changes from time to time. I googled Pair Commons Lang" and found it. I removed the link to prevent further downvotes :-( –
remipodApr 1 '13 at 17:52
Map
orList
classes, why should this be any different? A KeyValuePair is just a Map with one entry. – skaffman Jun 4 '10 at 10:21<X,Y>
, it's<Key,Value>
. He's not asking for an arbitraryPair
type, he's asking for aKeyValuePair
type. – skaffman Jun 4 '10 at 10:38