java集合之ArrayList、HashMap遍历
标签:string hello next cep integer 集合 迭代 通过 stat
1、遍历ArrayList
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListDemo1 {
public static void main(String[] args) {
List list = new ArrayList();
list.add("Hello ");
list.add("World ");
list.add("!!!");
// foreach遍历
for(String str:list){
System.out.print(str);
}
System.out.println();
// 将链表转为数组输出
String [] str1 = new String[list.size()];
list.toArray(str1);
for (int i =0; i){
System.out.print(str1[i]);
}
System.out.println();
// 用迭代器遍历
Iterator iterator = list.listIterator();
while (iterator.hasNext()){
System.out.print(iterator.next());
}
}
}
2、遍历HashMap
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapIteratorDemo1 {
public static void main(String[] args) throws Exception{
Map map = new HashMap();
map.put("壹",1);
map.put("贰",2);
map.put("叁",3);
//通过Map.keySet遍历key和value
for(String key:map.keySet()){
System.out.println("key="+key+",value="+map.get(key));
}
System.out.println("****************");
//通过Map.entrySet使用Iterator遍历key和value
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry entry = iterator.next();
System.out.println("key="+entry.getKey()+",value="+entry.getValue());
}
System.out.println("****************");
//容量大时,用
for(Map.Entry entry:map.entrySet()){
System.out.println("key="+entry.getKey()+",value="+entry.getValue());
}
System.out.println("****************");
for (int x :map.values()){
System.out.println(x);
}
}
}
java集合之ArrayList、HashMap遍历
标签:string hello next cep integer 集合 迭代 通过 stat
原文地址:https://www.cnblogs.com/cathycheng/p/13140741.html
评论