Java Stream流代替For循环 Java8特性之用Stream流代替For循环操作详解
四季人06 人气:0想了解Java8特性之用Stream流代替For循环操作详解的相关内容吗,四季人06在本文为您仔细讲解Java Stream流代替For循环的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,Stream流,Java,代替For循环,下面大家一起来学习吧。
准备一个实体类
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循环 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流
//遍历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);
先声明筛选条件,在遍历
//声明一个条件 学生年龄大于18 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层)
//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
加载全部内容