用java 8 API替换两个嵌套的for循环 [英] Replace two nested for loops with java 8 API

查看:884
本文介绍了用java 8 API替换两个嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下片段,我想知道是否以及如何用Streams / Java 8 API替换它

I have the following snippet and I wonder if and how it is possible to replace it with Streams/Java 8 API

for (State state : states) {
    for (City city : cities) {
        if (state.containsPoint(city.getLocation())) {
            System.out.printf("%30s is part of %-30s\n",
                    city.getName(), state.getName());
        }
    }
}


推荐答案

会是这样的:

// first loop
states.forEach(state -> { 
    // second loop for filtered elements
    cities.stream().filter(city -> state.containsPoint(city.getLocation())).forEach(city -> { 
        System.out.printf("%30s is part of %-30s\n", city.getName(), state.getName());
    });
});

这篇关于用java 8 API替换两个嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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