Rahul
Rahul

Reputation: 259

How to put key-value as key for other Map?

I want to put values in HashMap like below,

    map1.put("A",3);

    map1.put("A",5);
    map1.put("B",4);
    map1.put("B",8);

now I want to make ("A",3) key/value pair as key for other map like, let say ("A",3) is key1 same way for others map2.put(key1, abc);

same way for others. can you please help me to do like this???

Upvotes: 0

Views: 208

Answers (3)

Balázs Édes
Balázs Édes

Reputation: 13807

Or you can store them in a Pair like this:

class Pair
{
    public String first;
    public Integer second;

    public Pair(String first, Integer second)
    {
        this.first = first;
        this.second = second;
    }
}

Then create a HashMap of Pair - String pairs:

HashMap<Pair, String> map = new HashMap<Pair, String>();

Upvotes: 0

pb2q
pb2q

Reputation: 59607

You can get those (key, value) pairs as a set using the entrySet method. Iterate over that set and use the elements as keys in your other HashMap.

Something like this:

// given HashMap<String, Integer> map1:
for (Map.Entry<String, Integer> entry : map1.entrySet())
    map2.put(entry, "some string value");

Upvotes: 0

kosa
kosa

Reputation: 66637

You can get first hashMap entrySet and use it as key for second hashMap.

entrySet returns

Set view of the mappings contained in this map

For example,

1) Set firstMapEntries = map1.entrySet();

2) Create secondmap

3) Iterate firstMapEntries.

4)Add to second map secondMap.put(firstMapEntry, "abc")

Upvotes: 2

Related Questions