java queue遍历元素_Java基础--Stack,Queue和Map的遍历

总结

集合元素的遍历,最好使用foreach()

Stack的遍历

public class TestStack {

public static void main(String[] args) {

Stack s = new Stack();

for (int i = 0; i < 10; i++) {

s.push(i);

}

//集合遍历方式

for (Integer x : s) {

System.out.println(x);//输出0-9,这个顺序是压入的顺序

}

System.out.println("-----------");

//栈弹出遍历方式

// while (s.peek()!=null) { //不健壮的判断方式,容易抛异常,正确写法是下面的

while (!s.empty()) {

System.out.println(s.pop());//输出9-0,从栈顶到栈底

}

}

}

Queue的遍历

public class TestQueue {

public static void main(String[] args) {

Queue q = new LinkedBlockingQueue();

//初始化队列

for (int i = 0; i < 5; i++) {

q.offer(i);

}

//集合方式遍历,元素不会被移除

for (Integer x : q) {

System.out.println(x);//输出0-4

}

System.out.println("------------");

//队列方式遍历,元素逐个被移除

while (q.peek() != null) {

System.out.println(q.poll());//输出0-4

}

}

}

Map的遍历

public class TestMap {

public static void main(String[] args) {

Map map = new HashMap();

map.put("1", "a");

map.put("2", "b");

map.put("3", "c");

//最简洁、最通用的遍历方式

for (Map.Entry entry : map.entrySet()) {

System.out.println(entry.getKey() + " = " + entry.getValue());

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值