准备一个实体类
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
准备一个List集合
List<Student> list=new ArrayList<>();
Student s1=new Student();
s1.setName("张三");
s1.setAge(18);
list.add(s1);
Student s2=new Student();
s2.setName("李四");
s2.setAge(22);
list.add(s2);
传统的for循环
for (int i=0;i< list.size();i++){
System.out.println(list.get(i));
}
for(Student student: list){
System.out.println(student);
}
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
使用Stream流
list.stream().forEach(str->{
System.out.println(str.getName()+":"+str.getAge());
});
list.stream().filter(str -> !"李四".equals(str.getName())).forEach(str -> {
System.out.println(str.getName()+":"+str.getAge());
});
先声明筛选条件,在遍历
Predicate<Student> pred = (student) -> student.getAge() > 18;
selectStudent(list,pred);
private static void selectStudent(List<Student> list, Predicate<Student> pred) {
System.out.println("选出年龄大于18的学生:");
list.forEach(student -> {
if (pred.test(student)){
System.out.println(student.getName()+":"+student.getAge());
}
});
}
Stream操作 嵌套循环(2层)
List<Student> list = list1.stream().filter(student1 -> list2.stream()
.anyMatch(studnet2 -> student1.getName().equals(studnet2.getName()) ))
.collect(Collectors.toList());
System.out.println("stream操作筛选后的结果" + list.get(0).getName());
|