在文章开始之前,我们创建一个Student类,方便下面操作使用:
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age)
{
super();
this.name = name;
this.age = 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;
}
@Override
public String toString()
{
return "Student [name=" + name + ", age=" + age + "]";
}
}
先看一下 Stream< T > filter(Predicate super T> predicate);
的源码:
/**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* This is an intermediate
* operation.
*
* @param predicate a non-interfering,
* stateless
* predicate to apply to each element to determine if it
* should be included
* @return the new stream
*/
Stream filter(Predicate super T> predicate);
其实就是接受lambda,从流中排除某些元素。
比如筛选出年龄大于20岁的学生:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
class Test{
public static void main(String []args) {
List<Student> stuList = Arrays.asList(new Student("xiaoming",18),
new Student("xiaoli",22),
new Student("xiaozhang",19),
new Student("Tom",26),
new Student("Kevin",20),
new Student("Lucy",26)
);
Stream<Student> stream1 = stuList.stream().filter((stu) -> stu.getAge()>20);
stream1.forEach(System.out::println);
}
}
Output:
Student [name=xiaoli, age=22]
Student [name=Tom, age=26]
Student [name=Lucy, age=26]
截断流,使元素不超过limit中传入的数
比如筛选出年龄大于20岁,但不超过2个人数
Stream<Student> stream1 = stuList.stream().filter((stu) -> stu.getAge()>20).limit(2);
stream1.forEach(System.out::println);
output:
Student [name=xiaoli, age=22]
Student [name=Tom, age=26]
找到两个符合条件的就不继续找,有利于效率提高。
跳过元素,返回一个抛弃掉了前n个元素的流。若流中元素不足n个,则返回一个空流
Stream stream1 = stuList.stream().filter((stu) -> stu.getAge()>20).skip(1);
stream1.forEach(System.out::println);
去除重复元素,前提是重写hashcode和equals方法
我们新加入了三个重复的元素new Student("Lucy",26)
,并且在Student类重写了hashcode和equals方法。
class Test{
public static void main(String []args) {
List<Student> stuList = Arrays.asList(new Student("xiaoming",18),
new Student("xiaoli",22),
new Student("xiaozhang",19),
new Student("Tom",26),
new Student("Kevin",20),
new Student("Lucy",26),
new Student("Lucy",26),
new Student("Lucy",26)
);
Stream<Student> stream1 = stuList.stream().filter((stu) -> stu.getAge()>20).skip(1).distinct();
stream1.forEach(System.out::println);
}
}
Output:
Student [name=Tom, age=26]
Student [name=Lucy, age=26]