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

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

问题描述

是否可以使用Lambda Expression迭代 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(枚举,lambda) -expression); (介意导入静态功能)...

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

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

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