Java8特性之用Stream流代替For循环操作详解
程序员文章站
2022-07-05 21:46:56
目录准备一个list集合使用stream流stream操作 嵌套循环(2层)准备一个实体类public class student { private string name; priva...
准备一个实体类
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
到此这篇关于java8特性之用stream流代替for循环操作详解的文章就介绍到这了,更多相关java stream流代替for循环内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!