简体   繁体   English

如何将键值作为其他Map的关键?

[英]How to put key-value as key for other Map?

I want to put values in HashMap like below, 我想将值放在HashMap中,如下所示,

    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); 现在我想把(“A”,3)键/值对作为其他地图的关键,比方说(“A”,3)是key1,对于其他map2.put(key1,abc);

same way for others. 对他人也一样。 can you please help me to do like this??? 你能帮我这样做吗???

You can get first hashMap entrySet and use it as key for second hashMap. 您可以获取第一个hashMap entrySet并将其用作第二个hashMap的键。

entrySet returns entrySet返回

Set view of the mappings contained in this map 设置此映射中包含的映射的视图

For example, 例如,

1) Set firstMapEntries = map1.entrySet(); 1)设置firstMapEntries = map1.entrySet();

2) Create secondmap 2)创建第二个地图

3) Iterate firstMapEntries. 3)迭代firstMapEntries。

4)Add to second map secondMap.put(firstMapEntry, "abc") 4)添加到第二个映射secondMap.put(firstMapEntry,“abc”)

You can get those (key, value) pairs as a set using the entrySet method. 您可以使用entrySet方法将这些(键,值)对作为集合。 Iterate over that set and use the elements as keys in your other HashMap . 迭代该集合并将元素用作其他HashMap键。

Something like this: 像这样的东西:

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

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: 然后创建Pair - String对的HashMap:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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