一、遍历List
1、增强for循环
String[] arr = new String[] {"xx","yy","zz"};
for(String elt:arr) {
System.out.println(elt);
}
2、下标的方式
String[] arr = new String[] {"xx","yy","zz"};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
3、迭代器
List<String> list = new ArrayList<String>();
list.add("xx");
list.add("yy");
list.add("zz");
for (Iterator<String> iter = list.iterator();iter.hasNext();) {
String elt = iter.next();
System.out.println(elt);
}
二、遍历Set
1、增强for循环
Set<String> set = new HashSet<String>();
set.add("xx");
set.add("yy");
set.add("zz");
for(String elt:set) {
System.out.println(elt);
}
2、迭代器
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
三、遍历Map
1、增强for循环(Entry集合)
// 遍历Map:
Map<String, String> map = new HashMap<String, String>();
map.put("aa", "xx");
map.put("bb", "yy");
map.put("cc", "zz");
//1、增强的for循环(Entry集合)
for(Entry<String,String>entry:map.entrySet()) {
System.out.println(entry);
}
2、增强的for循环(Key集合)
// 2,增强的for循环(Key集合)
for(String key : map.keySet()){
System.out.println(key + " = " + map.get(key));
}
3、遍历值的集合
// 3,遍历值的集合
for(String value : map.values()){
System.out.println(value);
}