list和map是java集合中的必备类,当然他们的遍历也是至关重要的。
list的遍历:
1.for循环
for (Integer each : list) {
System.out.println(each);
}
2.iterator循环
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
3.正规的for循环
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
整个demo如下:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println("第一种方式:精简的for循环---------------");
for (Integer each : list) {
System.out.println(each);
}
System.out.println();
System.out.println("第二种方式:iterator指针---------------");
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println();
System.out.println("第三种方式:正常的for循环---------------");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println();
map的遍历:
使用entrySet()方法遍历:
for (Entry<String, String> each : map.entrySet()) {
System.out.println(each.getKey() + ":" + each.getValue());
}
demo如下:
Map<String, String> map = new HashMap<String, String>();
map.put("1", "小王");
map.put("2", "小李");
map.put("3", "小黑");
for (Entry<String, String> each : map.entrySet()) {
System.out.println(each.getKey() + ":" + each.getValue());
}