现在是有一个一多对应的映射.........如何通过hashmap去将所有的映射都对应起来呢例如
key value
a 1
a 2
a 3然后的话,怎么去得到 a 所对应的所有值呢???????另外的话,map的对象模型是怎么样的呢?
例如:
hashMap a = new hashMap();
a.put("one","1");
a.put("one","2");
a.put("one","3");然后我再
a.put("two","4");
a.put("two","5");
a.put("two","6");
这样的话,可以再找到one的映射吗?
刚开始学习map对map的操作不是很熟悉,求前辈指点
key value
a 1
a 2
a 3然后的话,怎么去得到 a 所对应的所有值呢???????另外的话,map的对象模型是怎么样的呢?
例如:
hashMap a = new hashMap();
a.put("one","1");
a.put("one","2");
a.put("one","3");然后我再
a.put("two","4");
a.put("two","5");
a.put("two","6");
这样的话,可以再找到one的映射吗?
刚开始学习map对map的操作不是很熟悉,求前辈指点
就像下面这样:
import java.util.*;public class Test1 {
public static void main(String[] args) {
HashMap<String, String> a = new HashMap<String, String>();
a.put("one", "1");
a.put("one", "2");
a.put("one", "3");
a.put("two", "4");
a.put("two", "5");
a.put("two", "6");
Set<Map.Entry<String, String>> s = a.entrySet();
Iterator<Map.Entry<String, String>> it = s.iterator();
while (it.hasNext()) {
System.out.println(it.next());
} }}如果需要一个a对应多个值,那么把这些值放到集合里,然后再放到Map里不就可以了?
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class Test { public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<String, List<String>>(); List<String> one = new ArrayList<String>();
one.add("1");
one.add("2");
one.add("3"); List<String> two = new ArrayList<String>();
two.add("4");
two.add("5");
two.add("6");
map.put("one", one);
map.put("two", two); // 通过 foreach 循环输出
// 遍历 map
for(Map.Entry<String, List<String>> entry : map.entrySet()) {
// 遍历 map 中 value 的 List
for(String str : entry.getValue()) {
System.out.println(entry.getKey() + " --> " + str);
}
}
}
}
key要唯一 value 只有是对象就行 例如:集合 数组 字符串等
Collection collection=map.values(); 返回值集合
Set set = map.keySet();返回键结合
注意: set 集合是不允许重复值的 这就反向说明key要唯一