遍历集合的方法总结

遍历list方法:

  1.普通for循环:for (int i = 0; i < list.length; i++){

            String temp = (String)list.get(i);

            System.out.println(temp);

          }

  2.增强for循环:for (String temp:list) {

            System.out.println(temp);    }

  3.使用迭代器:for (Iterator iter = list.iterator();iter.hasNext();) {

          String temp = (String) iter.next();
          System.out.println(temp);   }

  或         Iterator iter = list.iterator();

          while (iter.hasNext()) {
          Object obj = iter.next();
          iter.remove();//遍历时,删除集合中的元素
          System.out.println(obj);    }

 

 

遍历set方法:1.增强for循环:for (String temp:set) {

              System.out.println(temp);      }

       2.使用迭代器:for (Iterator iter = set.iterator();iter.hasNext();)                 

               String temp = (String)iter.next();

               System.out.println(temp);   }

 

遍历map方法:1.根据key获得value:  Map maps = new HashMap();

                  Set keySet = maps.keySet();
                  for (Integer i :keySet) {
                  System.out.println(maps.get(i).name);       }

       2.使用entrySet: Set> ss = maps.entrySet();

                for (Iterator iter = ss.iterator();iter.hasNext();) {
                Entry e = (Entry)iter.next();
                System.out.println(e.getKey()+":"+e.getValue());        }

 

你可能感兴趣的:(遍历集合的方法总结)