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

2022-09-01 15:40:40

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

将是这样的:

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

答案 2

推荐