ptikobj
ptikobj

Reputation: 2710

Java Dictionary value of type tuple

I want a Dictionary (HashTable, Map, ...) that has one key and several values.

I.e. I want something like

HashTable<Key, [value1, value2]>

How do I get this?

Upvotes: 2

Views: 3584

Answers (6)

John Pickup
John Pickup

Reputation: 5105

Google's Guava provides a multimap that does this. Javadoc

Upvotes: 1

helios
helios

Reputation: 13841

There's no such thing as tuples in Java Language, so you can use some of the proposals:

  • store an array
  • store a List, Set
  • store a custom object holding the two values

You also can make a fairly general object: Pair.

public Pair<A,B> {
  public Pair(A a, B b) {
   this.a = a;
   this.b = b;
  }
  public A a() { return a; }
  public B b() { return b; }
}

Upvotes: 0

thejh
thejh

Reputation: 45568

Make a new (non-public) class for your values or use multiple maps (propably slower).

Upvotes: 1

Scott W
Scott W

Reputation: 9872

How about HashTable<Key, List<Value>>?

Upvotes: 2

jjnguy
jjnguy

Reputation: 138864

The easiest way I think:

Map<Key, List<Value>>

If you would rather just have a tuple (pair, 3, or ...) you can create a Pair class.

class Pair<E,F, ...> {

    public E one;
    public F two;
    ...

}

And then use a Map like so:

Map<Key, Pair<Value, Value>>

Upvotes: 7

Chris Dennett
Chris Dennett

Reputation: 22721

Just store an array as the value with defined length?

Upvotes: 1

Related Questions