List、set以及map的遍歷方式的整理
阿新 • • 發佈:2019-01-09
@Test public void foreachSet() { Set setObj = new HashSet(); setObj.add("dsf"); setObj.add(1); setObj.add(5); //first: iterator Iterator iterator = setObj.iterator(); while (iterator.hasNext()) { System.out.println("set值: " + iterator.next()); } //second: for(int i...) for (Object obj : setObj) { System.out.println("obj值: " + obj); } }
@Test public void foreachList() { List listObj = new ArrayList(); listObj.add(1); listObj.add("88"); //first:iterator Iterator iterator = listObj.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } //second:for(int i....) for (int i = 0; i < listObj.size(); i++) { System.out.println(listObj.get(i)); } //third:foreach for (Object obj : listObj) { System.out.println(obj); } }
@Test public void foreachMap() { //first: 使用keySet遍歷map Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 5); map.put(2, 6); map.put(3, 7); for (Integer keyInt : map.keySet()) { Integer valueInt = map.get(keyInt); System.out.println("key1 : " + keyInt + " value1 : " + valueInt); } //second: 使用entrySet遍歷map Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet(); for (Map.Entry<Integer, Integer> entryObj : entrySet) { System.out.println("key2 : " + entryObj.getKey() + " value2 : " + entryObj.getValue()); } //third: 使用ITERATOR遍歷map Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); System.out.println("Key3 : " + entry.getKey() + " Value3 : " + entry.getValue()); } }