数据过滤类似于SQL中的WHERE语句,是在杂乱的数据中筛选出需要的数据。下面就介绍一下filter()方法。
filter()是Stream接口提供的一个过滤方法。该方法以lambda表达式的逻辑过滤流中的元素。若要展示数据需可以使用 Stream提供的collect()方法进行封装。
基本使用方法:
下面是一个简单的例子,展示了如和利用filter()过滤出3的倍数:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Filtertest {
public static void main(String[] args) {
List<Integer>list = new ArrayList<>();
for(int i = 1;i<=30;i ++){
list.add(i); //向集合中添加数据
}
printeach("过滤前" ,list);
Stream<Integer>stream = list.stream(); //获取集合流对象
stream= stream.filter(n-> n % 3 == 0); //过流出流中3的倍数(关键代码)
List<Integer>res = stream.collect(Collectors.toList());//将流重新封装成List集合
printeach("过滤后",res);
}
static void printeach(String S,List list)
{ System.out.print(S);
list.stream().forEach(n->{
System.out.print(n+" ");
}); //不要忘记分号
System.out.println(" ");
}
}
运行结果如下:
过滤前1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
过滤后3 6 9 12 15 18 21 24 27 30
2 .结合流处理用
filter()方法通常会和流处理一起用。而且过滤的不仅仅是数字。下面这个例子首先添加了一个员工集合。并记录了姓名,年龄,薪资,性别,部门。最后通过filter()方法找出了女性的员工。
代码如下:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class Streamprocess{
private String name;
private int age;
private double salary;
private String sex;
private String dept;
public Streamprocess(String name,int age,double salary,String sex, String dept)
{
this.name = name;
this.age =age;
this.salary = salary;
this.sex = sex;
this.dept = dept;
}
public String toString() {
return "name="+name+"age="+age+"salary="+salary+"sex="+sex+"dept="+dept;
}
public String getName() { return name;}
public int getAge() {return age;}
public double getSalary() {return salary;}
public String getSex() {return sex;}
public String getDept() {return dept;}
static List<Streamprocess>getEm(){
List<Streamprocess>list = new ArrayList<Streamprocess>();
list.add(new Streamprocess("小一",50,4000,"男","一部"));
list.add(new Streamprocess("小二",10,4000,"女","一部"));
list.add(new Streamprocess("小三",30,5000,"男","二部"));
list.add(new Streamprocess("小四",40,5000,"男","二部"));
list.add(new Streamprocess("小五",60,3000,"女","三部"));
list.add(new Streamprocess("小六",10,4000,"男","三部"));
return list;
}
public static void main(String[] args) {
List<Streamprocess>list1 = Streamprocess.getEm();
Stream<Streamprocess>stream = list1.stream();
stream = stream.filter(people->"女".equals(people.getSex()));
List<Streamprocess>result = stream.collect(Collectors.toList());
for(Streamprocess emp:result) {
System.out.println(emp);
}
}
}
运行结果:
name=小二age=10salary=4000.0sex=女dept=一部
name=小五age=60salary=3000.0sex=女dept=三部
希望对你有帮助~~~