HashMap:不能有重复的键,键相同值覆盖。无序:元素的存入和取出顺序不一致。
TreeMap:不能有重复的键
LinkedHashMap:不能有重复的键。可对元素进行排序。
keySet():返回集合中键的set视图
values():返回集合中值的collection视图
entrySet():返回集合中包含的映射关系的set视图
1. 通过获取键集合获取map集合中的值
public static void main(String[] args) {
Map<Object,Object> map = new HashMap<Object,Object>();//创建map集合
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
Set<Object> keySet = map.keySet();//获取键集合
Iterator<Object> it = keySet.iterator();
while(it.hasNext()){
Object key = it.next();
Object value = map.get(key);
System.out.println(value);
}
}
2. 通过获取值集合获取map集合中的值
public static void main(String[] args) {
Map<Object,Object> map = new HashMap<Object,Object>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
Collection<Object> values = map.values();//获取值集合
Iterator<Object> it = values.iterator();
while(it.hasNext()){
Object value = it.next();
System.out.println(value);
}
}
3. 通过获取映射关系获取map集合中的值
public static void main(String[] args) {
Map<Object,Object> map = new HashMap<Object,Object>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
Set<Entry<Object,Object>> entrySet = map.entrySet();//获取映射关系集合
Iterator<Entry<Object, Object>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry keyAndValue = (Map.Entry)it.next();
Object key = keyAndValue.getKey();
Object value = keyAndValue.getValue();
System.out.println(key+"="+value);
}
}