首页 > 编程语言 > 详细

Java基础--Stack,Queue和Map的遍历

时间:2020-04-26 02:22:27      阅读:67      评论:0      收藏:0      [点我收藏+]

总结

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

Stack的遍历

public class TestStack {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<Integer>();
        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<Integer> q = new LinkedBlockingQueue<Integer>();
        //初始化队列
        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<String, String> map = new HashMap<String, String>();
        map.put("1", "a");
        map.put("2", "b");
        map.put("3", "c");

        //最简洁、最通用的遍历方式
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }

    }
}

Java基础--Stack,Queue和Map的遍历

原文:https://www.cnblogs.com/swifthao/p/12776431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!