简体   繁体   中英

Associating two values to a single key in a java HashMap

I am trying to associate two values of different datatypes [one long and the other a string] to a single key in a Java HashMap. I have looked around and suggestions to similar problems include, using the MultiValuedMap from the Apache Collections Framework or using the MultiMap from Guava. However I think these may be overkill plus I would not like to add extra binaries to my system.

Is there anything wrong with defining a class such as:

class X {
    long value1;
    String value2;
    X(long v, String w) { this.value1 = v; this.value2 = w;}
}

While inserting into the HashMap do this:

X obj = new X(1000, "abc");
map.add("key", obj)

Are there any glaring drawbacks with this approach? I am looking for a solution that scales well in lookup.

Thanks!

Nothing wrong with your approach. As Java lacks a tuple class, you can define your own generically (instead of your class X ):

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
} 

see also Using Pairs or 2-tuples in Java

The usage would then be as follows:

    Map<String,Tuple<Long,String>> map = new HashMap<>();
    Tuple<Long,String> obj = new Tuple<>(1000L, "abc");
    map.put("key", obj);

It's totally fine. You can store any object as the value in a Map , in this case you simply use your own class to wrap two individual values.

As long as you don't use your custom class as the key, you're already done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM