I like how Java has a Map where you can define the types of each entry in the map, for example
.
What I\'m looking for is a type
To anyone developing for Android, you can use android.util.Pair. :)
Expanding on the other answers a generic immutable Pair should have a static method to avoid cluttering your code with the call to the constructor:
class Pair<L,R> {
final L left;
final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
static <L,R> Pair<L,R> of(L left, R right){
return new Pair<L,R>(left, right);
}
}
if you name the static method "of" or "pairOf" the code becomes fluent as you can write either:
list.add(Pair.of(x,y)); // my preference
list.add(pairOf(x,y)); // use with import static x.y.Pair.pairOf
its a real shame that the core java libraries are so sparse on such things that you have to use commons-lang or other 3rd parties to do such basic stuff. yet another reason to upgrade to scala...
Apache Crunch also has a Pair
class:
http://crunch.apache.org/apidocs/0.5.0/org/apache/crunch/Pair.html
I mean, even though there is no Pair
class in Java there is something pretty simmilar: Map.Entry
Map.Entry Documentation
This is (simplifying quite a bit) what HashMap
, or actually any Map
stores.
You can create an instance of Map
store your values in it and get the entry set. You will end up with a Set<Map.Entry<K,V>>
which effectively is what you want.
So:
public static void main(String []args)
{
HashMap<String, Integer> values = new HashMap<String,Integer>();
values.put("A", 235);//your custom data, the types may be different
//more data insertions....
Set<Map.Entry<String,Integer>> list = values.entrySet();//your list
//do as you may with it
}
I was going to ask if you would not want to just use a List<Pair<T, U>>
? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheers
What about com.sun.tools.javac.util.Pair?