List遍歷方式,Map的遍歷方式
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class ForTest {
public static void main(String[] args) {
// list集合的遍歷
List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
System.out.println("");
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.print(it.next());
}
System.out.println("");
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
System.out.print(iterator.next());
}
System.out.println("");
// map集合的遍歷
Map map = new HashMap<>();
map.put("1", "蘋果");
map.put("2", "香蕉");
map.put("3", "檸檬");
// for迴圈遍歷
for (int j = 1; j <= map.size(); j++) {
String num = String.valueOf(j);
System.out.print(map.get(num));
}
System.out.println();
// 通過獲取所有的key按照key來遍歷
Set set = map.keySet();
for (Object iString : map.keySet()) {
System.out.print(map.get(iString));
}
System.out.println();
// 通過entrySet遍歷
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = (Entry<String, String>) iterator.next();
System.out.println("鍵:" + entry.getKey() + "值:" + entry.getValue());
}
}
}