28

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());
        }
    }
}
3
  • 6
    Just as a note, while it's possible to convert such loop with the Stream API, I don't think you gain in readability in this case and I would stick with this for-loop. Commented May 21, 2015 at 14:49
  • Yeah, definitely. But I was curious how a solution could look like Commented May 21, 2015 at 15:18
  • @AlexisC. - Makes sense. Like this nested for loop example, are there any general guidelines on when it is better to NOT use lambdas and streams ? Commented Mar 7, 2020 at 21:13

1 Answer 1

43

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());
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

That was fast. Thanks i will give it a try
You can omit streaming the states and simply use states.forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.