在 Java 8 中迭代枚举 [英] Iterate an Enumeration in Java 8

查看:36
本文介绍了在 Java 8 中迭代枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 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)…

这篇关于在 Java 8 中迭代枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆