遍历集合,使用Iterator。
1.遍历HashMap:
1 void func() { 2 HashMap<String, Integer> hashMap = new HashMap<>(); 3 hashMap.put("Tom", 123); 4 hashMap.put("FF", 22); 5 hashMap.put("CC", 21); 6 Iterator<Entry<String, Integer>> iterator = hashMap.entrySet() 7 .iterator(); 8 while (iterator.hasNext()) { 9 Map.Entry<String, Integer> entry = iterator.next(); 10 System.out.println("key:" + entry.getKey() + " values:" 11 + entry.getValue()); 12 13 } 14 }
输出结果:
key:FF values:22
key:CC values:21
key:Tom values:123
2.遍历HashSet:
1 void funcSet() { 2 Set<String> set = new HashSet<>(); 3 set.add("Tom"); 4 set.add("CC"); 5 set.add("Naruto"); 6 Iterator<String> iterator = set.iterator(); 7 while (iterator.hasNext()) { 8 String string = (String) iterator.next(); 9 System.out.println(string); 10 } 11 }
输出:
CC
Tom
Naruto
3.遍历List:
1 void funcList() { 2 List<String> list = new ArrayList<>(); 3 list.add("Tom"); 4 list.add("CC"); 5 list.add("Narr"); 6 Iterator<String> iterator = list.iterator(); 7 while (iterator.hasNext()) { 8 String string = (String) iterator.next(); 9 System.out.println(string); 10 } 11 }
输出:
Tom
CC
Narr