Replace two nested for loops with java 8 API

2019-03-25 07:33发布

问题:

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

回答1:

Will be something like that:

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