简体   繁体   中英

Is there a way to merge two for loops using Streams in java 8?

I have two lists in which one is of type String and the other is of some entity object. How to iterate through those two lists or compare it by using java 8

List<Admin> admin= new ArrayList<>();

for (Admin ah : subProducers) {
    for (String value : values) {
        if (ah.getFirstName().contains(value) || ah.getLastName().contains(value)) {
            admin.add(ah);
        }
    }
}

I am currently using the for loop to verify that condition, I don't find any better way to combine it using java 8 streams.

Something like an anyMatch with nested streams :

subProducers.stream()
            .filter(a -> values.stream()
                               .anyMatch(b -> a.getFirstName().contains(b)
                                           || a.getLastName().contains(b)))
            .collect(Collectors.toList())

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