Java案例怎么使用Foreach遍历?

wen java案例 24

本文目录导读:

Java案例怎么使用Foreach遍历?

  1. 遍历数组
  2. 遍历集合(List)
  3. 遍历Set集合
  4. 遍历Map集合
  5. 遍历二维数组
  6. 遍历自定义对象集合
  7. foreach与Lambda表达式(Java 8+)
  8. 注意事项

在Java中,foreach循环(也称为增强型for循环)是一种简洁遍历数组和集合的方式,下面通过具体案例详细说明:

遍历数组

public class ForEachArray {
    public static void main(String[] args) {
        // 遍历一维数组
        int[] numbers = {1, 2, 3, 4, 5};
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        // 输出: 1 2 3 4 5
        System.out.println();
        // 遍历字符串数组
        String[] names = {"张三", "李四", "王五"};
        for (String name : names) {
            System.out.println("姓名: " + name);
        }
    }
}

遍历集合(List)

import java.util.ArrayList;
import java.util.List;
public class ForEachList {
    public static void main(String[] args) {
        // 创建List集合
        List<String> fruits = new ArrayList<>();
        fruits.add("苹果");
        fruits.add("香蕉");
        fruits.add("橘子");
        // 使用foreach遍历
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

遍历Set集合

import java.util.HashSet;
import java.util.Set;
public class ForEachSet {
    public static void main(String[] args) {
        Set<Integer> scores = new HashSet<>();
        scores.add(85);
        scores.add(92);
        scores.add(78);
        scores.add(92); // 重复元素不会添加
        // foreach遍历Set(无顺序)
        for (int score : scores) {
            System.out.println("成绩: " + score);
        }
    }
}

遍历Map集合

import java.util.HashMap;
import java.util.Map;
public class ForEachMap {
    public static void main(String[] args) {
        Map<String, Integer> studentScores = new HashMap<>();
        studentScores.put("张三", 90);
        studentScores.put("李四", 85);
        studentScores.put("王五", 95);
        // 方式1:遍历键值对
        for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        System.out.println("---");
        // 方式2:遍历键
        for (String name : studentScores.keySet()) {
            System.out.println("学生: " + name);
        }
        System.out.println("---");
        // 方式3:遍历值
        for (int score : studentScores.values()) {
            System.out.println("分数: " + score);
        }
    }
}

遍历二维数组

public class ForEach2DArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        // 遍历二维数组
        for (int[] row : matrix) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
        // 输出:
        // 1 2 3 
        // 4 5 6 
        // 7 8 9 
    }
}

遍历自定义对象集合

import java.util.ArrayList;
import java.util.List;
// 自定义类
class Student {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
}
public class ForEachObject {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("小明", 18));
        students.add(new Student("小红", 19));
        students.add(new Student("小刚", 20));
        // 遍历自定义对象
        for (Student s : students) {
            System.out.println("学生: " + s.getName() + 
                             ", 年龄: " + s.getAge());
        }
    }
}

foreach与Lambda表达式(Java 8+)

import java.util.ArrayList;
import java.util.List;
public class ForEachLambda {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("北京");
        cities.add("上海");
        cities.add("广州");
        // 传统foreach
        System.out.println("传统方式:");
        for (String city : cities) {
            System.out.println(city);
        }
        // Lambda表达式(Java 8新特性)
        System.out.println("\nLambda方式:");
        cities.forEach(city -> System.out.println(city));
        // 方法引用
        System.out.println("\n方法引用方式:");
        cities.forEach(System.out::println);
    }
}

注意事项

  1. 不能修改元素值:foreach无法修改集合/数组中的元素(基本类型除外)
  2. 不能删除元素:遍历过程中删除元素会抛异常
  3. 无法获取索引:如果需要索引,使用传统for循环
// 错误示例 - 不能修改集合元素
List<String> list = new ArrayList<>();
for (String s : list) {
    s = "new"; // 这只是修改了局部变量s,不影响list中的元素
}

这就是Java中foreach遍历的常见用法,希望对你有帮助!

抱歉,评论功能暂时关闭!