Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using List Stream filter vs for loop

In java 8 you can now use filter on a list to get another list based on the Predicate you supply.

so lets say I have normal for loop logic like this

for(Person p : personList){
    if(p.getName().Equals("John")){
         //do something with this person
    }
}

now using a filter like this

List<Person> johnList = personList.stream()
    .filter(p -> p.getName().Equals("John"))
    .collect(Collectors.toList()); 

for(Person john : johnList){
    //do something with this person
}

it seems like using a filter would cause more overhead than using just a regular for loop because its not only looping through the entire list the first time but then you have to loop through the filtered list and do what you want with that filtered list.

Am I incorrect in how this works?

like image 426
tyczj Avatar asked Aug 13 '26 20:08

tyczj


1 Answers

Doing it the way you're doing it would indeed not be a good idea. But that's not how you're supposed to do it. The proper way would be

personList.stream()
          .filter(p -> p.getName().equals("John"))
          .forEach(p -> doSomethingWithPerson(p));

which does a single pass on the list and does not create any additional list.

like image 57
JB Nizet Avatar answered Aug 15 '26 08:08

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!