Guava迭代器,迭代列表对象中的列表

Gob*_*ffi 13 java iterator guava

我有以下示例代码,其中包含3个嵌套的for循环.

for(Continent continent : continentList) 
{
    for(Country country : continent.getCountries())
    {
        for(City city : country.getCities())
        {
            //Do stuff with city objects
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用Guava和迭代器来模仿这个嵌套的for循环?我一直试图找到一个没有太多运气的合适例子,我想知道是否有人可以帮助我?我的一位同事提到使用过滤器.

编辑:修复了示例代码中的小错误

ig0*_*774 11

正如Peter Lawrey评论的那样,这几乎肯定会像嵌套循环一样简单.此外,Guava文档提供了此警告:

命令式代码应该是您的默认设置,是Java 7的首选.除非您完全确定以下其中一项,否则不应使用功能惯用语:

  • 使用功能惯用法将为整个项目节省大量代码.将函数的定义移动到另一个文件或常量也无济于事.
  • 为了提高效率,您需要对转换后的集合进行延迟计算的视图,并且无法满足显式计算的集合.此外,您已阅读并重读了Effective Java,第55项,除了遵循这些说明之外,您还实际进行了基准测试,以证明此版本更快,并且可以引用数字来证明它.

在使用Guava的功能实用程序时,请确保传统的命令式处理方式不易读取.试着把它写出来.真是太糟糕了吗?那比你想要尝试的荒谬笨拙的功能方法更具可读性吗?

但是,如果你坚持忽略建议,你可以使用像这样的怪物(注意我实际上没有尝试编译或运行它):

FluentIterable.from(continentList)
    .transform(new Function<Continent, Void>() {
        public Void apply(Continent continent) {
            return FluentIterable.from(continent.getCountries())
                .transform(new Function<Country, Void>() {
                    public Void apply(Country country) {
                        return FluentIterable.from(country.getCities())
                            .transform(new Function<City, Void>() {
                                public Void apply(City city) {
                                    // do stuff with city object
                                    return null;
                                }
                            });
                    }
                });
        }
    });
Run Code Online (Sandbox Code Playgroud)

现在问问自己:你想保持哪个?哪个会最有效?

Guava的功能成语有一些有效的用例.替换Java for循环,甚至嵌套for循环,不是其中之一.

  • 使用[`FluentIterable.transformAndConcat()`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/FluentIterable.html),您可以链接转换而不是嵌套但是他们. (4认同)

Rik*_*ikH 8

您可以为以下内容定义静态函数:
•Continent,Continents或Functions中的getCountries()
•Country,Countries或Functions中的getCities()

现在你可以做点什么......

FluentIterable.from(continentList)
    .transformAndConcat(Continent.getCountriesFunction())
    .transformAndConcat(Country.getCitiesFunction())
    . //filter //tranform //find //toList() //etc.
Run Code Online (Sandbox Code Playgroud)

如果:
•您经常使用番石榴(更多).
•对于定义函数和谓词的位置有一定的规则/想法.
•具有可以过滤或搜索的各种(复杂)事物.
然后它可以是一个伟大的福音,可以使许多情况更容易.我知道我很高兴我做到了.

如果你稀疏地使用它,那么我将不得不同意@Louis Wasserman.然后这不值得麻烦.此外,将函数和谓词定义为匿名内部类,就像其他示例一样......真的很难看.


art*_*tol 2

不,没有简单的方法。此外,它会比问题中的 for-each 循环更详细。

请参阅http://code.google.com/p/guava-libraries/issues/detail?id=218#c5以及http://code.google.com/p/guava-libraries/wiki/FunctionalExplained中的注意事项