用java 8 API替换两个嵌套的for循环

时间:2015-05-21 14:19:38

标签: java loops lambda java-8

我有以下片段,我想知道是否以及如何用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());
        }
    }
}

1 个答案:

答案 0 :(得分:25)

会是这样的:

// 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());
    });
});