我有两个哈希图,我想填充第三个哈希图,其中的键将是第一个哈希图的值,而值将是拆分为数组的第二个哈希图的值。
即:
hashmap1 = {1=e1, 2=e2}
hashmap2 = {10=word1-word2-word3, 20=word4-word5-word6}
the result:
hashmap3 = {e1=word1-word2-word3, e2=word4-word5-word6}
这是我到目前为止所做的:
static HashMap<Integer, String> catnamecatkeys = new HashMap<Integer, String>();
static HashMap<Integer, String> keywords = new HashMap<Integer, String>();
static HashMap<String, String> tempHash = new HashMap<String, String>();
static HashMap<String, String[]> hash = new HashMap<String, String[]>();
static String[] arr;
public static void main(String[] args) {
catnamecatkeys.put(1, "e1");
catnamecatkeys.put(2, "e2");
keywords.put(1, "word1-word2-word3");
keywords.put(2, "word4-word5-word6");
for (int key : catnamecatkeys.keySet()) {
tempHash.put(catnamecatkeys.get(key),null);
}
for(String tempkey: tempHash.keySet()){
tempHash.put(tempkey,keywords.entrySet().iterator().next().getValue());
arr = tempHash.get(tempkey).split("-");
hash.put(tempkey, arr);
}
System.out.println(tempHash);
for (String hashkey : hash.keySet()) {
for (int i = 0; i < arr.length; i++) {
System.out.println(hashkey + ":" + hash.get(hashkey)[i]);
}
}
}
但输出是:
hashmap3 = {e1=word1-word2-word3, e2=word1-word2-word3}
有任何想法吗?
最佳答案
您应该在循环外初始化Iterator,这是完整的示例-
static HashMap<Integer, String> catnamecatkeys = new HashMap<Integer, String>();
static HashMap<Integer, String> keywords = new HashMap<Integer, String>();
static HashMap<String, String> tempHash = new HashMap<String, String>();
static HashMap<String, String[]> hash = new HashMap<String, String[]>();
static String[] arr;
public static void main(String[] agrs)
{
catnamecatkeys.put(1, "e1");
catnamecatkeys.put(2, "e2");
keywords.put(1, "word1-word2-word3");
keywords.put(2, "word4-word5-word6");
for (int key : catnamecatkeys.keySet()) {
tempHash.put(catnamecatkeys.get(key),null);
}
Set<Entry<Integer,String>> set = keywords.entrySet();
Iterator<Entry<Integer, String>> iterator= set.iterator();
for(String tempkey: tempHash.keySet()){
tempHash.put(tempkey,iterator.next().getValue());
arr = tempHash.get(tempkey).split("-");
hash.put(tempkey, arr);
}
System.out.println(tempHash);
for (String hashkey : hash.keySet()) {
for (int i = 0; i < arr.length; i++) {
System.out.println(hashkey + ":" + hash.get(hashkey)[i]);
}
}
}
关于java - 具有键和值的HashMap使用Java等于其他两个哈希图的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10033336/