DroidPest
DroidPest

Reputation: 394

Map with multi values

I basically want 2 values on 1 map if possible or something equivalent. I want to store this info

Map<K,V1,V2> sample = new HasMap<K,V1,V2>
(Key - caller) = 26
(value 1 - callee) = 55
(value 2 - seconds) = 550
sample(26,55,550)

the only other way i see how i can do this is

Map(k, arraylist(v2))

having the position in the arraylist as V1 but this will take forever to search if i would want to find what callers have called a specific callee.

i have also read this HashMap with multiple values under the same key but i do not understand how to do this.

Upvotes: 0

Views: 140

Answers (4)

Janny
Janny

Reputation: 691

Create a bean for your value like below

  class Value {
    VariableType val1;
    VariableType val2;
    ...
    }

Then we can create a map like below

Map<K,Value> valueSample = new HashMap<K,Value>();
valueSample .put(new K(), new Value());

We need to set the value in Value calss by setter or constructor

Upvotes: 2

Debojit Saikia
Debojit Saikia

Reputation: 10622

One solution is to create a wrapper object (it was given in the discussion link that you have in your question) to hold values v1 and v2:

class ValueWrapper {
V1Type v1;
V2Type v2;
...
}

Now you can map your keys to the instances of this wrapper:

Map<K,ValueWrapper> sample = new HashMap<K,ValueWrapper>();
sample.put(new K(), new ValueWrapper());

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You can do like this.

  Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
  List<Integer> list =new ArrayList<Integer>();
  list.add(55);
  list.add(550);
  //Adding value to the map
  map.put(26, list);

  //getting value from map
  List<Integer> values = map.get(26);

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19284

If all values are <V1, V2> you can use Entry as value:

Map<K,Map.Entry<V1,V2>> sample = new HasMap<K,Map.Entry<V1,V2>>();

Create Entry<V1,V2> and put it with the relevant key.

Another solution (and even better one) is to create your own value class.

Upvotes: 0

Related Questions