遍历集合
-
List集合的遍历
- 定义集合并向集合存放元素,这里存放随机数组
1 List<Integer> list = new ArrayList<Integer>(); 2 3 Random r = new Random(); 4 int j; 5 for( int i = 0; i < 10; i++ ) { 6 j = r.nextInt(100);//小于100的随机数 7 list.add(j);//向list集合添加随机数 8 }
- 增加循环遍历
1 for( Integer i : list) { 2 System.out.print(i+"\t"); 3 }
- 迭代器迭代
1 Iterator<Integer> iterator = list.iterator(); 2 while( iterator.hasNext()) { 3 System.out.print(iterator.next()+"\t"); 4 }
-
Set集合的遍历
- 定义集合并向集合存放元素
1 Set<String> set = new TreeSet<String>(); 2 3 String []strings = {"北京","广州","昆明","大理","成都"};5 for( int i = 0; i < strings.length; i++ ) { 6 set.add(strings[i]); 7 }
- 增加循环遍历
1 for(String s : set ) { 2 System.out.print(s+"\t"); 3 }
- 迭代器迭代
1 Iterator<String> iterator = set.iterator(); 2 while(iterator.hasNext()) { 3 System.out.print(iterator.next()+"\t"); 4 }
-
Map集合的遍历
- 定义集合并存放元素
1 Map<Integer, String > map = new HashMap<Integer, String>(); 2 int []key = {0,1,2,3,4}; 3 String []name = {"lihua","popo","kejo","nace","jake"}; 4 5 for(int i = 0; i < key.length; i++ ) { 6 map.put(key[i], name[i]); 7 }
- 增强循环遍历
1 for(Integer i : map.keySet()) { 2 String outName = map.get(i); 3 System.out.print("["+i + " "+ outName+"] "); 4 }
- 迭代器遍历
1 System.out.println("迭代器遍历"); 2 Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); 3 while( iterator.hasNext()) { 4 System.out.print(iterator.next()); 5 }