public static void main(String[] args) { ListFor(2); } public static void ListFor(int a){ //測試list集合遍歷(直接有四種遍歷方式) final ArrayList<Integer> integers = ...
public static void main(String[] args) {
ListFor(2);
}
public static void ListFor(int a){
//測試list集合遍歷(直接有四種遍歷方式)
final ArrayList<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
integers.add(4);
//測試set集合遍歷(一般轉換成數組進行遍歷)
HashSet<String> strings = new HashSet<>();
strings.add("張三");
strings.add("123");
strings.add("張三");
//測試map集合遍歷
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"麻婆豆腐");
map.put(2,"紅燒牛肉");
map.put(3,"獅子頭");
//1.經典循壞遍歷:效率最高遍歷快,但是不適用於所有集合實用範圍小
if (a==1) {
//list集合遍歷
for (int i = 0; i < integers.size(); i++) {
System.out.println(integers.get(i));
}
//set集合遍歷
Object[] objects = strings.toArray();
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
//2.迭代器遍歷:遍歷時可以操作元素,但是相對於其他遍歷方式效率比較慢
if (a==2){
//list集合遍歷
Iterator<Integer> iterator = integers.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next());
}
//set集合遍歷
Iterator<String> iterator1 = strings.iterator();
while (iterator1.hasNext()){
System.out.println(iterator1.next());
}
//map集合遍歷
Iterator<Map.Entry<Integer, String>> iterator2 = map.entrySet().iterator();
while (iterator2.hasNext()){
Map.Entry<Integer, String> entry = iterator2.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
//3.加強for迴圈遍歷:代碼簡潔,但是不能操作元素
if (a==3){
//list集合遍歷
System.out.println("加強for迴圈遍歷結果:");
for (Integer integer:integers){
System.out.println(integer);
}
//set集合遍歷
for (String str:strings){
System.out.println(str);
}
//map集合遍歷
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
//4.lambda表達式遍歷
if (a==4){
System.out.println("lambda表達式遍歷");
// JDK8之後才有的遍歷
// integers.forEach(integer-> System.out.println(integer));
}
}