1.List
(1) for循环
for(int i = 0 ; i < list.size() ; i ++) System.out.println(list.get(i)); (2)foreach循环
for(String s: list) System.out.println(s); (3)Iterator迭代器
Iterator<String> iterator =list.iterator();
while (iterator.hasNext())
{
String m = iterator.next();
System.out.println(m);
}
2.Set
(1)for each循环
for(String s: set1) System.out.println(s); (2)iterator迭代器
Iterator<String> iterator = list.iterator();
while (iterator.hasNext())
{
String m = iterator.next();
System.out.println(m);
}3.Map
(1)for each遍历Map的Key
for (String key : map.keySet())
{
Integer value = map.get(key);
System.out.println(key + " - " + value);
}(2)for each遍历可以和value
for (Map.Entry<String, Integer> entry : map.entrySet())
{
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " - " + value);
}4.Queue队列
(1)for each遍历
for(int x: q) System.out.printf("%d ",x); (2)iterator迭代器
Iterator it = q.iterator();
while(it.hasNext()) System.out.printf("%d ",it.next()); (3)while循环
while(!q.isEmpty()) System.out.printf("%d ",q.poll()); 5,Deque双端队列
(1)while循环遍历同时进行出队操作
String item = "";
while((item = deque.pollLast()) != null) System.out.println(item); (2)for each遍历(仅从队头开始)
for(String s:deque) System.out.println(s); (3)Iterator迭代器
Iterator it = deque.iterator();
while(it.hasNext()) System.out.println(it.next()); 6,Stack栈
(1)for each循环
for(String s : stack) System.out.println(s); (2)while循环
while (!stack.isEmpty()) System.out.println(stack.pop()); (3)Iterator迭代器遍历
Iterator it = stack.iterator();
while(it.hasNext()) System.out.println(it.next());
本文介绍了Java中几种主要集合类型的遍历方式,包括List的for循环、foreach和Iterator,Set的foreach和Iterator遍历,Map的Key和Entry遍历,以及Queue和Deque的多种遍历和操作方法,还有Stack的遍历和弹出操作。
745

被折叠的 条评论
为什么被折叠?



