遍历List
public void iteratorList(){
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
//方法1 使用iterator遍历
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String value = iterator.next();
System.out.println(value);
}
//方法2 传统for循环
for(int i=0;i<list.size();i++){
String value = list.get(i);
System.out.println(value);
}
//方法3 增强for循环
for(String str : list){
System.out.println(str);
}
}
遍历Map
public void iteratorMap(){
Map<String,String> map = new HashMap<>();
map.put("1","a");
map.put("2","b");
//方法1 传统遍历集合方法 keySet
//取key的set
Set<String> set1 = map.keySet();
//取迭代器遍历对应的值
Iterator<String> it1 = set1.iterator();
while (it1.hasNext()){
String key = it1.next();
String value = map.get(key);
System.out.println(key + ":" + value);
}
//方法2 传统遍历集合方法 entrySet
Set<Map.Entry<String,String>> set2 = map.entrySet();
//取得迭代器遍历出对应的值
Iterator<Map.Entry<String,String>> it2 = set2.iterator();
while(it2.hasNext()){
Map.Entry<String,String> entry = it2.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
//方法3 增强for循环遍历map集合 keySet
Set<String> set3 = map.keySet();
for(String str : set3){
String key = str;
String value = map.get(key);
System.out.println(key + ":" + value);
}
//方法4 增强for循环遍历map集合 entySet
Set<Map.Entry<String,String>> set4 = map.entrySet();
for(Map.Entry<String,String> entry : set4){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
}
所有博客均为自己学习的笔记。如有错误敬请理解。