温馨提示×

java枚举类型如何遍历

小樊
106
2024-11-19 18:47:53
栏目: 编程语言

在Java中,可以使用以下方法遍历枚举类型:

  1. 使用for-each循环遍历枚举类型的所有值:
public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumTraversal {
    public static void main(String[] args) {
        for (Weekday day : Weekday.values()) {
            System.out.println(day);
        }
    }
}
  1. 使用EnumSet和Iterator遍历枚举类型的所有值:
import java.util.EnumSet;
import java.util.Iterator;

public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumTraversal {
    public static void main(String[] args) {
        EnumSet<Weekday> weekdays = EnumSet.allOf(Weekday.class);
        Iterator<Weekday> iterator = weekdays.iterator();

        while (iterator.hasNext()) {
            Weekday day = iterator.next();
            System.out.println(day);
        }
    }
}
  1. 使用Java 8的Stream API遍历枚举类型的所有值:
import java.util.stream.Stream;

public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumTraversal {
    public static void main(String[] args) {
        Stream<Weekday> weekdays = Weekday.stream();

        weekdays.forEach(System.out::println);
    }
}

以上三种方法都可以遍历枚举类型的所有值。你可以根据自己的需求和编程风格选择合适的方法。

0