Iterating over Enum Values in Java – 在Java中对枚举值进行迭代

最后修改: 2017年 5月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In Java, an Enum is a datatype that helps us assign a predefined set of constants to a variable.

在Java中,Enum是一种数据类型,它可以帮助我们将一组预定义的常量分配给一个变量。

In this quick tutorial, we’ll learn different ways that we can iterate over an Enum in Java.

在这个快速教程中,我们将学习在Java中迭代Enum的不同方法。

2. Iterating Over Enum Values

2.在Enum值上进行迭代

Let’s first define an Enum, so we can create some simple code examples:

让我们首先定义一个Enum,这样我们就可以创建一些简单的代码示例。

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

Enums don’t have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Enum没有迭代的方法,像forEach()iterator()。相反,我们可以使用由values()方法返回的Enum值阵列。

2.1. Iterate Using for Loop

2.1.使用for循环进行迭代

First, we can simply use the old-school for loop:

首先,我们可以简单地使用老式的for循环。

for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) { 
    System.out.println(day); 
}

2.2. Iterate Using Stream

2.2.使用Stream进行迭代

We can also use java.util.Stream to perform operations on the Enum values.

我们还可以使用java.util.Stream来对Enum值进行操作。

To create a Stream, we have two options. The first is using Stream.of:

要创建一个Stream,我们有两个选择。第一个是使用Stream.of

Stream.of(DaysOfWeekEnum.values());

The second is using Arrays.stream:

第二种是使用Arrays.stream

Arrays.stream(DaysOfWeekEnum.values());

Let’s extend the DaysOfWeekEnum class to create an example using Stream:

让我们扩展DaysOfWeekEnum类,使用Stream创建一个例子。

public enum DaysOfWeekEnum {
    
    SUNDAY("off"), 
    MONDAY("working"), 
    TUESDAY("working"), 
    WEDNESDAY("working"), 
    THURSDAY("working"), 
    FRIDAY("working"), 
    SATURDAY("off");

    private String typeOfDay;

    DaysOfWeekEnum(String typeOfDay) {
        this.typeOfDay = typeOfDay;
    }
	
    // standard getters and setters 

    public static Stream<DaysOfWeekEnum> stream() {
        return Stream.of(DaysOfWeekEnum.values()); 
    }
}

Now we’ll write an example in order to print the non-working days:

现在我们来写一个例子,以便打印非工作日的情况。

public class EnumStreamExample {

    public static void main() {
        DaysOfWeekEnum.stream()
        .filter(d -> d.getTypeOfDay().equals("off"))
        .forEach(System.out::println);
    }
}

The output we get when we run this is:

当我们运行这个时,得到的输出是。

SUNDAY
SATURDAY

2.3. Iterate Using forEach()

2.3.使用forEach()进行迭代

The forEach() method was added to the Iterable interface in Java 8. So all the java collection classes have implementations of a forEach() method. In order to use these with an Enum, we first need to convert the Enum to a suitable collection. We can use Arrays.asList() to generate an ArrayList, which we can then loop around using the forEach() method:

在Java 8中,forEach()方法被添加到Iterable接口。所以所有的java集合类都有forEach()方法的实现。为了在Enum中使用这些方法,我们首先需要将Enum转换为一个合适的集合。我们可以使用Arrays.asList()来生成一个ArrayList,然后我们可以使用forEach()方法进行循环。

Arrays.asList(DaysOfWeekEnum.values())
  .forEach(day -> System.out.println(day));

2.4. Iterate Using EnumSet

2.4.使用EnumSet进行迭代

EnumSet is a specialized set implementation that we can use with Enum types:

EnumSet是一个专门的集合实现,我们可以使用Enum类型。

EnumSet.allOf(DaysOfWeekEnum.class)
  .forEach(day -> System.out.println(day));

2.5. Using an ArrayList of Enum Values

2.5.使用ArrayListEnum

We can also add the values of an Enum to a List. This allows us to manipulate the List like any other:

我们还可以将Enum的值添加到List中。这使我们能够像其他一样操作List

List<DaysOfWeekEnum> days = new ArrayList<>();
days.add(DaysOfWeekEnum.FRIDAY);
days.add(DaysOfWeekEnum.SATURDAY);
days.add(DaysOfWeekEnum.SUNDAY);
for (DaysOfWeekEnum day : days) {
    System.out.println(day);
}
days.remove(DaysOfWeekEnum.SATURDAY);
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
    System.out.println("Saturday is no longer in the list");
}
for (DaysOfWeekEnum day : days) {
    System.out.println(day);
}

We can also create an ArrayList by using Arrays.asList().

我们也可以通过使用Arrays.asList()创建一个ArrayList

However, as the ArrayList is backed by the Enum values array, it’ll be immutable, so we can’t add or remove items from the List. The remove in the following code would fail with an UnsupportedOperationException:

然而,由于ArrayList是由Enum值数组支持的,它将是不可改变的,所以我们不能从List中添加或删除项目。以下代码中的删除将以UnsupportedOperationException失败。

List<DaysOfWeekEnum> days = Arrays.asList(DaysOfWeekEnum.values());
days.remove(0);

3. Conclusion

3.结论

In this article, we discussed various ways to iterate over an Enum using forEach, Stream, and the for loop in Java.

在这篇文章中,我们讨论了在Java中使用forEach、Streamfor循环来迭代Enum的各种方法。

If we need to perform any parallel operations, Stream is a good option. Otherwise, there’s no restriction on which method to use.

如果我们需要执行任何并行操作,Stream是一个不错的选择。否则,对使用哪种方法没有任何限制。

As always, the code for all the examples explained here can be found over on GitHub.

一如既往,这里解释的所有例子的代码都可以在GitHub上找到