JAVA中遍历Map和Set方法,取出map中所有的key

时间:2022-06-07 19:18:04

Java遍历Set集合

1、迭代器遍历:   
Set<String> set = new HashSet<String>();   
Iterator<String> it = set.iterator();   
while (it.hasNext()) {   
  String str = it.next();   
  System.out.println(str);   
}   
2、for循环遍历:   
for (String str : set) {   
      System.out.println(str);   
}   
3、优点还体现在泛型 假如 set中存放的是Object   
Set<Object> set = new HashSet<Object>();   
for循环遍历:   
for (Object obj: set) {   
      if(obj instanceof Integer){   
                int aa= (Integer)obj;   
             }else if(obj instanceof String){   
               String aa = (String)obj   
             }   
              ........   
}   

Java中遍历Map

Map<String, String> map = new HashMap(); 

        map.put("郑州", "河南"); 
        map.put("长沙", "湖南"); 

        //第一種  
        Set<String> set = map.keySet(); //取出所有的key值
        for (String key:set) {
            System.out.println("第一种:"+map.get(key)); 
        }
        
        //第二种 
        Set<Map.Entry<String, String>> entryseSet=map.entrySet(); 
        for (Map.Entry<String, String> entry:entryseSet) {
            System.out.println("第二种:"+entry.getKey()+":"+entry.getValue());
        }
        
        //第三种
        Iterator it = map.keySet().iterator();
        while(it.hasNext()){
           //int key = (Integer) it.next();
           String value = map.get(it.next());
           System.out.println("第三种:"+value);
        }

JAVA中遍历Map和Set方法,取出map中所有的key