在 Java 8 中迭代枚举

2022-01-24 00:00:00 iteration lambda enumeration java-8 java

是否可以使用 Lambda 表达式迭代 Enumeration?以下代码片段的 Lambda 表示形式是什么:

Is it possible to iterate an Enumeration by using Lambda Expression? What will be the Lambda representation of the following code snippet:

Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

while (nets.hasMoreElements()) {
    NetworkInterface networkInterface = nets.nextElement();

}

我没有在其中找到任何流.

I didn't find any stream within it.

推荐答案

如果您不喜欢 Collections.list(Enumeration) 将整个内容复制到(临时)列表中在迭代开始之前,您可以通过一个简单的实用方法帮助自己:

In case you don’t like the fact that Collections.list(Enumeration) copies the entire contents into a (temporary) list before the iteration starts, you can help yourself out with a simple utility method:

public static <T> void forEachRemaining(Enumeration<T> e, Consumer<? super T> c) {
  while(e.hasMoreElements()) c.accept(e.nextElement());
}

然后您可以简单地执行 forEachRemaining(enumeration, lambda-expression);(注意 import static 功能)...

Then you can simply do forEachRemaining(enumeration, lambda-expression); (mind the import static feature)…

相关文章