Java 集合 Stack、Queue、Map插入、移除和遍历

1、Stack 操作

  // Stack 类表示后进先出(LIFO)的对象堆栈
		Stack stack = new Stack();
		// 把数据项压入堆栈顶部
		stack.push("a");
		stack.push("b");
		stack.push("c");

		// peek() 查看堆栈顶部的对象,但不从堆栈中移除它
		System.out.println(stack.peek());
		
		System.out.println("-----------------------------");
		
		// 集合方式遍历,元素不会被移除
		for (String s : stack) {
			System.out.println(s);
		}
		
		System.out.println("-----------------------------");
		
		// 栈弹出遍历方式,元素会被移除
		// empty() 测试堆栈是否为空
		while (!stack.empty()) {
			// pop() 移除堆栈顶部的对象,并作为此函数的值返回该对象
			System.out.println(stack.pop());
		}

    结果:

c
-----------------------------
a
b
c
-----------------------------
c
b
a

 

2、Queue 操作

 

  Queue queue = new LinkedBlockingDeque();
		// 将指定的元素插入此队列(如果立即可行且不会违反容量限制),
		// 当使用有容量限制的队列时,此方法通常要优于 add(E),
		// 后者可能无法插入元素,而只是抛出一个异常。
		queue.offer("a");
		queue.offer("b");
		queue.offer("c");

		// 获取但不移除此队列的头;如果此队列为空,则返回 null
		System.out.println(queue.peek());
		
		System.out.println("----------------------");
		
		// 集合方式遍历,元素不会被移除
		for (String s : queue) {
			System.out.println(s);
		}
		
		System.out.println("----------------------");
		
		// 队列方式遍历,元素逐个被移除
		while (!queue.isEmpty()) {
			// 获取并移除此队列的头,如果此队列为空,则返回 null
			System.out.println(queue.poll());
		}

 结果:

a
----------------------
a
b
c
----------------------
a
b
c

 

 3、Map 操作

 

  // 将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。
		Map map = new HashMap();
		map.put(1, "a");
		map.put(2, "b");
		map.put(3, "c");
		
		// 获取键对应的值
		System.out.println("获取map的键为2的值 : " + map.get(2));
		
		System.out.println("-----------------------");
		
		// Entry方式遍历map,简洁
		for (Map.Entry entry : map.entrySet()) {
			System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
		}
		
		System.out.println("------------------------");
		
		// 这种遍历方式有点繁琐
		Iterator> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = it.next();
			System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
		}
		
		System.out.println("------------------------");
		
		// Key遍历
		Iterator itKey = map.keySet().iterator();
		while (itKey.hasNext()) {
			 System.out.println(itKey.next());
		}
		
		System.out.println("------------------------");

		// Value遍历
		Iterator itValue = map.values().iterator();
		while (itValue.hasNext()) {
			 System.out.println(itValue.next());
		}
		
		System.out.println("------------------------");
		
		// map 移除元素
		// 如果存在一个键的映射关系,则将其从此映射中移除
		System.out.println(map.remove(2));

 结果:

获取map的键为2的值 : b
-----------------------
Key : 1, Value : a
Key : 2, Value : b
Key : 3, Value : c
------------------------
Key : 1, Value : a
Key : 2, Value : b
Key : 3, Value : c
------------------------
1
2
3
------------------------
a
b
c
------------------------
b

 

你可能感兴趣的:(java)