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

总结

集合元素的遍历,最好使用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());
        }

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