我有两个散列映射,我想填充第三个散列映射,这些散列映射的键将是第一个散列映射的值,这些值将是拆分到一个数组中的第二个散列映射的值。即:
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}有什么想法吗?
发布于 2012-04-06 02:04:17
你应该在循环之外初始化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]);
}
}
}发布于 2012-04-06 01:56:41
你的问题是这一行:
keywords.entrySet().iterator().next().getValue()将始终返回相同的keywords HashMap条目。尝试使用以下内容构建新的hashmap:
for (int i = 1; i < 3; i++) {
tempHash.put(catnamecatkeys.get(i), keywords.get(i));
}发布于 2012-04-06 04:20:18
根据你的例子,你有:
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}hashmap1和hashmap2之间没有公共键,所以我们尝试将键为"1“的hashmap1中的值与键为"10”的hashmap2中的值关联起来。除非保留有关如何将条目从hashmap1映射到hashmap2的附加信息,否则无法做到这一点。如果使用保证迭代顺序与插入顺序相同的映射(例如LinkedHashMap),则此附加信息可以是映射中的插入顺序。
https://stackoverflow.com/questions/10033336
复制相似问题