Java8特性之用Stream流代替For循环操作详解

时间:2021-07-20 21:20:01

准备一个实体类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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集合

?
1
2
3
4
5
6
7
8
9
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循环

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//for循环
for (int i=0;i< list.size();i++){
    System.out.println(list.get(i));
}
 
//增强for循环
for(Student student: list){
    System.out.println(student);
}
//迭代器
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()){
    System.out.println(iterator.next());
}

使用Stream流

?
1
2
3
4
5
6
7
8
9
10
11
//遍历List集合
 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());
 });
  //操作对象,拼接
//String collect=list.stream().map(student->student.getName()).collect(Collectors.joining(",","前","后"));
// System.out.println(collect);

先声明筛选条件,在遍历

?
1
2
3
4
//声明一个条件 学生年龄大于18
Predicate<Student> pred = (student) -> student.getAge() > 18;
//调用方法
selectStudent(list,pred);
?
1
2
3
4
5
6
7
8
9
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层)

?
1
2
3
4
5
//java 8 stream操作 嵌套循环
        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());

但是不建议foreach套foreach

到此这篇关于Java8特性之用Stream流代替For循环操作详解的文章就介绍到这了,更多相关Java Stream流代替For循环内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/sxh06/article/details/119987984