1、根据键找值
public static void main(String[] args) {
//创建集合对象
Map<String ,Integer> map=new HashMap<String ,Integer>();
//创建元素并添加到集合
map.put("hello", 1);
map.put("world", 2);
Set <String> set=map.keySet();
for(String key:set){
Integer value=map.get(key);
System.out.println(key+"___"+value);
}
}
2、根据键值对对象找键和值方法1:
键值对对象可以比喻成结婚证,而键和值就像是结婚证上的2个人名。
public static void main(String[] args) {
//创建集合对象
Map<String ,Integer> map=new HashMap<String ,Integer>();
//创建元素并添加到集合
map.put("hello", 1);
map.put("world", 2);
//1、获取所有键值对对象的集合
Set<Map.Entry<String , Integer>> set=map.entrySet();
//2、获取Iterator对象,并用此对象的方法遍历键值对对象
Iterator <Map.Entry<String, Integer>> iter=set.iterator();
while(iter.hasNext()){
Map.Entry<String, Integer> me=iter.next();
//3、根据键值对对象获取键和值
System.out.println(me.getKey()+me.getValue());
}
}
3、根据键值对对象找键和值方法2:
public static void main(String[] args) {
//创建集合对象
Map<String ,Integer> map=new HashMap<String ,Integer>();
//创建元素并添加到集合
map.put("hello", 1);
map.put("world", 2);
//1、获取所有键值对对象的集合
Set <Map.Entry<String, Integer>> set=map.entrySet();
//2、foreach遍历键值对对象的集合,得到每一个键值对对象
for(Map.Entry<String, Integer> me:set){
//3、根据键值对对象获得键和值
System.out.println(me.getKey()+"————"+me.getValue());
}
}