Search code examples
java-8java-stream

Java streams - dealing with multiple for loop and multiple if and else conditions


Is it possible to achieve this requirement using Java streams? For example: I have a list of countries. I want to iterate through for loop and for each country I want to call a method to get all states of that particular country. Inside the inner for loop, I want to prepare a new list which contains states which starts with letter "A". Can you please advise whether it is possible in streams? If yes, how?

I tried using map and filters but it didn't help. Any help would be appreciated. Thanks


Solution

  • Yes, it is possible using flatMap:

    @Getter
    @Setter
    private static class Country {
        private List<State> states;
    }
    
    @Getter
    @Setter
    private static class State {
        private String name;
    }
    
    private static List<String> filterStates(List<Country> countries, String start) {
        return countries.stream()
                .map(Country::getStates)
                .flatMap(List::stream)
                .map(State::getName)
                .filter(name -> name.startsWith(start))
                .collect(Collectors.toList());
    }