使用列表流过滤器vs for循环

tyc*_*czj 3 java list java-stream

在java 8中,您现在可以使用列表上的过滤器根据Predicate您提供的内容获取另一个列表.

所以我可以说我有像这样的循环逻辑

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

现在使用这样的过滤器

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

for(Person john : johnList){
    //do something with this person
}
Run Code Online (Sandbox Code Playgroud)

似乎使用过滤器会比仅使用常规for循环导致更多的开销,因为它不仅第一次循环遍历整个列表,而且你必须循环遍历过滤的列表并使用该过滤列表执行您想要的操作.

我的错误是如何工作的?

JB *_*zet 6

按照你的方式做它确实不是一个好主意.但那不是你应该怎么做的.正确的方法是

personList.stream()
          .filter(p -> p.getName().equals("John"))
          .forEach(p -> doSomethingWithPerson(p));
Run Code Online (Sandbox Code Playgroud)

它在列表上执行单个传递,并且不会创建任何其他列表.