JAVA遍历map元素
第一种:
?
另外 我们可以先把hashMap 转为集合Collection,再迭代输出,不过得到的对象
public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); HashMap<Object,Object> hash = new HashMap<Object,Object>(); TreeMap<Object,Object> treeMap = new TreeMap<Object,Object>(); list.add("a"); list.add("b"); list.add("c"); hash.put(3, 3); hash.put(4, 4); hash.put(5, 5); hash.put(6, 6); hash.put(1, 1); hash.put(2, 2); treeMap.put(1, 1); treeMap.put(2, 2); treeMap.put(3, 3); treeMap.put(4, 4); treeMap.put(5, 5); treeMap.put(6, 6); //list遍历 for(String m: list){ System.out.println(m); } // hashmap entrySet() 遍历 for(Map.Entry<Object,Object> m: hash.entrySet()){ System.out.println(m.getKey()+"---"+m.getValue()); } //hashmap keySet() 遍历 for(Object m: hash.keySet()){ System.out.println(m+"---"+hash.get(m)); } // treemap keySet()遍历 for(Object m: treeMap.keySet()){ System.out.println(m+"---"+treeMap.get(m)); }}??