Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace two nested for loops with 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());
        }
    }
}
like image 538
tplacht Avatar asked May 21 '15 14:05

tplacht


1 Answers

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());
    });
});
like image 106
Vartlok Avatar answered Nov 03 '22 13:11

Vartlok