user1621988
user1621988

Reputation: 4335

How do i store many Values with one Key

I want to store 3 values in 1 key. a Hashmap can only hold 1 key, 1 value, so that can not be used. So what other ways do I have to get from the one key the Value A/B/C.

Key: String

Values: String/String/int

Upvotes: 2

Views: 6492

Answers (4)

RNJ
RNJ

Reputation: 15552

Try

Map<Integer, List<yourObject>> m = new HashMap<>();

Then you will need to check if the list is present for a key. if so add to the list. Else create an ArrayList and add it

For example:

public add(String key, MyObj myobj){
    if (this.contains(key) ) { 
        this.get(key).add(myObj);
    }else {
        List<MyObject> list = new ArrayList<MyObject>();
        list.add(myObj);
        m.put(key, list);
    }
}

Upvotes: 0

Ian Dallas
Ian Dallas

Reputation: 12741

Create an object to hold your 3 values and then the new object is your value in the Key-value pair.

Here is a sample implementation:

class TripleValue {
    String A;
    String B;
    int C;

    public TripleValue(String a, String b, int c) {
        A = a;
        B = b;
        C = c;
    }
}

public static void main() {
    Map<String, TripleValue> myMap = new HashMap<String, TripleValue>(); 
    myMap.put("SomeKey", new TripleValue("String1", "String2", 10));

}

Upvotes: 11

Martyn Jones
Martyn Jones

Reputation: 118

Java framework doesn't support Multimap, there is a way around it, see below.

Map<Object,ArrayList<Object>> multiMap = new HashMap<Object,ArrayList<Object>>();

Also take a look at this library Guava-libraries

Upvotes: 0

kosa
kosa

Reputation: 66637

One of the way may be use either ArrayList/Set as value for the key.

Example:

List myTempList = new ArrayList();
myTempList.add("Hi");
myTempList.add("Hello");
myTempList.add("How are you");

myMap.key("key", myTempList);

Another approach is, if you know that number of values for each key are always going to be same, then you can create a holder object and set values to that object and put it in map.

Upvotes: 5

Related Questions