List的三种遍历方式:
public class TestList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("孙悟空");
list.add("唐三藏");
list.add("猪八戒");
list.add("沙悟净");
String listString = list.toString();
System.out.println(listString);
Integer size = list.size();
for (int i = 0; i < size; i++) {
String value1 = list.get(i);
System.out.println(value1);
}
System.out.println("==========================");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String value2 = iterator.next();
System.out.println(value2);
}
System.out.println("==========================");
for (String string : list) {
System.out.println(string);
}
}}
// 第一种方式遍历list集合:for循环
Integer size = list.size();
for (int i = 0; i < size; i++) {
String value1 = list.get(i);
System.out.println(value1);
}
// 第二种方式遍历list集合:iterator 迭代器
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String value2 = iterator.next();
System.out.println(value2);
}
// 第三种方式遍历list集合:foreach
for (String string : list) {
System.out.println(string);
}
Map的三种遍历方式:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("孙悟空", 1);
map.put("唐三藏", 2);
map.put("猪八戒", 3);
map.put("沙悟净", 4);
Set<String> keySet = map.keySet();
for (String key : keySet) {
Integer value = map.get(key);
System.out.println("键:"+ key + "值:"+ value);
}
Set<Entry<String, Integer>> set = map.entrySet();
for (Entry<String, Integer> entry : set) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("键:"+ key + "值"+value);
}
Iterator<Entry<String, Integer>> entrySet = map.entrySet().iterator();
while (entrySet.hasNext()) {
Entry<String, Integer> entry = entrySet.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("键:" + key + " " + "值:" + value);
}
}
// map遍历操作的第一种方法:keyset + foreach
// 采用keyset方法通过key值获取value值---》效率低
Set<String> keySet = map.keySet();
for (String key : keySet) {
Integer value = map.get(key);
System.out.println("键:"+ key + "值:"+ value);
}
// map遍历操作的第二种方式:map.entrySet();+foreach 方法进行遍历
Set<Entry<String, Integer>> set = map.entrySet();
for (Entry<String, Integer> entry : set) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("键:"+ key + "值"+value);
}
// map遍历操作的第三种方式:map.entrySet() +迭代器
Iterator<Entry<String, Integer>> entrySet = map.entrySet().iterator();
while (entrySet.hasNext()) {
Entry<String, Integer> entry = entrySet.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("键:" + key + " " + "值:" + value);
}
}
所有的方法都是卸载main方法之中的。