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

Java 使用列表流过滤器vs for循环,java,list,java-stream,Java,List,Java Stream,在Java8中,您现在可以根据您提供的谓词对列表使用过滤器来获取另一个列表 假设我有这样的正常for循环逻辑 for(Person p : personList){ if(p.getName().Equals("John")){ //do something with this person } } List<Person> johnList = personList.stream() .filter(p -> p.getName()

在Java8中,您现在可以根据您提供的
谓词
对列表使用过滤器来获取另一个列表

假设我有这样的正常for循环逻辑

for(Person p : personList){
    if(p.getName().Equals("John")){
         //do something with this person
    }
}
List<Person> johnList = personList.stream()
    .filter(p -> p.getName().Equals("John"))
    .collect(Collectors.toList()); 

for(Person john : johnList){
    //do something with this person
}
现在使用这样的过滤器

for(Person p : personList){
    if(p.getName().Equals("John")){
         //do something with this person
    }
}
List<Person> johnList = personList.stream()
    .filter(p -> p.getName().Equals("John"))
    .collect(Collectors.toList()); 

for(Person john : johnList){
    //do something with this person
}
List johnList=personList.stream()
.filter(p->p.getName().Equals(“John”))
.collect(Collectors.toList());
个人(约翰:约翰列表){
//对这个人做点什么
}
似乎使用过滤器会比只使用常规for循环带来更多的开销,因为它不仅第一次在整个列表中循环,而且还必须在过滤列表中循环,并对过滤列表执行所需操作


我的工作原理是否不正确?

以你现在的方式做确实不是一个好主意。但这不是你应该做的。正确的方法是

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

它只在列表上传递一次,不创建任何其他列表。

是的,因为您只完成了一半的工作。将第一个循环转换为Java8,结果是

personList.stream()
    .filter(p -> p.getName().Equals("John"))
    .forEach(person -> // ...);

无需“收集”过滤后的元素。

如有疑问,请进行基准测试。