Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
Jeeva D Avatar asked Jan 27 '23 13:01

Jeeva D


1 Answers

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())
like image 130
Naman Avatar answered Jan 29 '23 02:01

Naman