集合是java的终点部分,觉得map集合相对难掌握一些,所以上手练习了一下map集合的取出方式。
有生疏的同学快来巩固下~
- package exercises;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class MapDemo {
- public static void main(String[] args) {
- Map<Integer, String> map = new HashMap<Integer, String>();
- map.put(1, "abc");
- map.put(2, "bcd");
- map.put(3, "cde");
- map.put(4, "abcde");
- // getElement_1(map);
- getElement_2(map);
- }
- /**
- * 通过keySet获取map集合元素
- *
- * @param map
- */
- private static void getElement_1(Map<Integer, String> map) {
- Set<Integer> keySet = map.keySet();
- Iterator<Integer> it = keySet.iterator();
- while (it.hasNext()) {
- int key = it.next();
- String value = map.get(key);
- System.out.println(key + ":" + value);
- }
- }
- /**
- * 通过EntrySet获取集合元素
- *
- * @param map
- */
- private static void getElement_2(Map<Integer, String> map) {
- Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
- Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
-
- while (it.hasNext()) {
- Map.Entry<Integer, String> me = it.next();
- int key = me.getKey();
- String value = me.getValue();
- System.out.println(key + ":" + value);
- }
- }
- }
复制代码 |