简体   繁体   中英

Check if value from one list is present in another list using stream

I have List<RegionCountry> regionCountries of:

class RegionCountry {
    Region region;
    List<Country> countries;
   }

And Region and Country looks like:

class Region {
    Long regionId;
    String regionName;
}

class Country {
    Long countryId;
    String countryName;
}

Each Region have multiple countries within them. I am getting List<Long> countryIds and List<Long> regionIds from the UI which I want to compare against this regionCountries . So I did something like:

List<RegionCountry> filteredList = regionCountries
                            .stream()
                            .filter(regionCountry -> regionIds.contains(regionCountry.getRegion().getRegionId()))
                            .filter(regionCountry -> regionCountry.getCountries()
                                                    .stream()
                                                    .allMatch(country -> countryIds.contains(country.getCountryId())))
                            .collect(Collectors.toList());
                        

But it is not returning anything. I am trying to figure out how to compare List<Long> countryIds with List<Country> countries of RegionCountry . Is there any better approach to do it in Java 8 or 8+ using stream API ? Or can it be simplified by using any other approach?

The presented code seems to be fine and working, so the actual datasets need to be checked if they meet the provided condition: regionIds contain rc.regionId AND countryIds contain IDs of all countries.

Online demo (using record instead of classes to avoid boilerplate code) :

non-filtered
RegionCountry[region=Region[regionId=1, regionName=Europe], countries=[Country[countryId=1, countryName=Albania], Country[countryId=2, countryName=Andorra], Country[countryId=6, countryName=Germany]]]
RegionCountry[region=Region[regionId=3, regionName=America], countries=[Country[countryId=15, countryName=Canada], Country[countryId=16, countryName=US]]]
region ids: [3, 1]
country ids: [1, 2, 3, 15, 6]
filtered
RegionCountry[region=Region[regionId=1, regionName=Europe], countries=[Country[countryId=1, countryName=Albania], Country[countryId=2, countryName=Andorra], Country[countryId=6, countryName=Germany]]]

A minor optimization would be to use Set instead of List for regionIds , countryIds to make faster checks with Set::contains .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM