Java8 Stream用法详解
Posted liduchang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8 Stream用法详解相关的知识,希望对你有一定的参考价值。
1.概述
Stream 的原理:将要处理的元素看做一种流,流在管道中传输,并且可以在管道的节点上处理,包括过滤筛选、去重、排序、聚合等。元素流在管道中经过中间操作的处理,最后由最终操作得到前面处理的结果。
集合有两种方式生成流:
- stream() − 为集合创建串行流
- parallelStream() - 为集合创建并行流
- 中间操作主要有以下方法(此类型方法返回的都是 Stream):map (mapToInt, flatMap 等)、 filter、
distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered - 终止操作主要有以下方法:forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、
max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、
iterator
首先为了说明 Stream 对对象集合的操作,新建一个 Student 类(学生类), 覆写了 equals() 和 hashCode() 方法
public class Student {
private Long id;
private String name;
private int age;
private String address;
public Student() {
}
public Student(Long id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Student student = (Student) o;
return age == student.age && Objects.equals(id, student.id) && Objects.equals(name, student.name)
&& Objects.equals(address, student.address);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age, address);}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
1.1.filter(筛选)
/**
* 利用Stream筛选处符合条件的集合
* @param student
* @return
*/
private static List<Student> testFilter() {
Student s1=new Student(1L,"肖战",15,"浙江");
Student s2=new Student(2L,"王一博",15,"湖北");
Student s3=new Student(3L,"样子",17,"北京");
Student s4=new Student(4L,"李贤",17,"浙江");
List<Student> student=new ArrayList<Student>();
student.add(s1);
student.add(s2);
student.add(s3);
student.add(s4);
//筛选年龄大于15的学生
return student.stream().filter(s->s.getAge()>15).collect(Collectors.toList());
//筛选居住在在浙江的学生
// return student.stream().filter(s->"浙江".equals(s.getAddress())).collect(Collectors.toList());
}
1.2.map(转换)
/**
* 集合转换
* @param student
*/
private static void testMap(List<Student> student) {
//在地址前面加上部分信息,只获取地址输出
List<String> address=student.stream().map(s->"地址是:"+s.getAddress()).collect(Collectors.toList());
address.forEach(a->System.out.println(a));
}
1.3.distinct(去重)
/**
* 去重(基本类型)
* @param student
*/
private static void testDistinct1() {
List<String> list=Arrays.asList("111","222","111","333","444","222");
list.stream().distinct().forEach(s->System.out.println(s));;
// list.forEach(s->System.out.println(s));
}
/**
* 去重(引用对象)
* 可以看出,两个重复的 “肖战” 同学进行了去重,
* 这不仅因为使用了 distinct()方法,
* 而且因为 Student 对象重写了 equals 和
* hashCode()方法, 否则去重是无效的
*/
private static void testDistinct2() {
Student s1=new Student(1L,"肖战",15,"浙江");
Student s7=new Student(1L,"肖战",15,"浙江");
Student s2=new Student(2L,"王一博",15,"湖北");
Student s3=new Student(3L,"样子",17,"北京");
Student s4=new Student(4L,"李贤",18,"浙江");
Student s8=new Student(4L,"李贤",18,"浙江");
Student s5=new Student(2L,"李一鸣",16,"广州");
Student s6=new Student(1L,"张锋",13,"湛江");
List<Student> student=new ArrayList<Student>();
student.add(s1);
student.add(s7);
student.add(s8);
student.add(s2);
student.add(s3);
student.add(s4);
student.add(s5);
student.add(s6);
student.stream().distinct().forEach(s->System.out.println(s));
}
1.4.sorted(去重)
/**
* 排序(默认排序)
*/
private static void testSorted() {
List<String> list=Arrays.asList("111","333","222");
list.stream().sorted().forEach(s->System.out.println(s));
}
/**
* 集合排序(指定规则)
*/
private static void testSorted2() {
Student s1=new Student(1L,"肖战",15,"浙江");
Student s7=new Student(1L,"肖战",15,"浙江");
Student s2=new Student(2L,"王一博",15,"湖北");
Student s3=new Student(3L,"样子",17,"北京");
Student s4=new Student(4L,"李贤",18,"浙江");
Student s8=new Student(4L,"李贤",18,"浙江");
Student s5=new Student(2L,"李一鸣",16,"广州");
Student s6=new Student(1L,"张锋",13,"湛江");
List<Student> student=new ArrayList<Student>();
student.add(s1);
student.add(s7);
student.add(s8);
student.add(s2);
student.add(s3);
student.add(s4);
student.add(s5);
student.add(s6);
//指定排序规则,先按照学生的 id 进行降序排序,再按照年龄进行降序排序
student.stream()
.sorted((stu1,stu2)->Long.compare(stu2.getId(),stu1.getId())) //按照id进行倒叙排序
.sorted((stu1,stu2)->Integer.compare(stu2.getAge(),stu1.getAge())) //按照年龄进行倒叙排序
.forEach(s->System.out.println(s));
}
1.5.limit(限制返回的个数)
/**
* 限制返回的个数
* 集合limit,返回前几个元素
*/
private static void testlimit() {
List<String> list=Arrays.asList("111","222","333");
List<String> list2=list.stream().limit(2).collect(Collectors.toList());
list2.forEach(s->System.out.println(s));
}
1.6.skip(删除前几个元素)
/**
* 集合skip,删除前n个元素
*/
private static void testSkip() {
List<String> list=Arrays.asList("333","222","111");
List<String> collect = list.stream().skip(2).collect(Collectors.toList());
collect.forEach(s->System.out.println(s));
}
1.7.reduce(将集合中的每一个元素聚合成一条数据)
/**
* 集合Reduce,将集合中的每一个元素聚合成一条数据
*/
private static void testReduce() {
List<String> list=Arrays.asList("欢","迎","你");
String reduce = list.stream().reduce("北京",(a,b)->a+b);
System.out.println(reduce);
}
1.8.min(求集合中的最小值)
/**
* 求min集合中元素的最小值
* 求所有学生中年龄最小的一个,max 同理,求最大值。
*/
private static void testMin() {
Student s1=new Student(1L,"肖战",15,"浙江");
Student s7=new Student(1L,"肖战",15,"浙江");
Student s2=new Student(2L,"王一博",15,"湖北");
Student s3=new Student(3L,"样子",17,"北京");
Student s4=new Student(4L,"李贤",18,"浙江");
Student s8=new Student(4L,"李贤",18,"浙江");
Student s5=new Student(2L,"李一鸣",16,"广州");
Student s6=new Student(1L,"张锋",13,"湛江");
List<Student> student=new ArrayList<Student>();
student.add(s1);
student.add(s7);
student.add(s8);
student.add(s2);
student.add(s3);
student.add(s4);
student.add(s5);
student.add(s6);
//求年龄最小的人
Student student2 = student.stream().min((stu1,stu2)->Integer.compare(stu1.getAge(),stu2.getAge())).get();
System.out.println(student2);
}
1.8.anyMatch/allMatch/noneMatch(匹配)
/**
* 测试匹配
*anyMatch/allMatch/noneMatch(匹配)
*anyMatch:Stream 中任意一个元素符合传入的 predicate,返回 true
allMatch:Stream 中全部元素符合传入的 predicate,返回 true
noneMatch:Stream 中没有一个元素符合传入的 predicate,返回 true
*/
private static void testMatch() {
Student s1=new Student(1L,"肖战",15,"浙江");
Student s7=new Student(1L,"肖战",15,"浙江");
Student s2=new Student(2L,"王一博",15,"湖北");
Student s3=new Student(3L,"样子",17,"北京");
Student s4=new Student(4L,"李贤",18,"浙江");
Student s8=new Student(4L,"李贤",18,"浙江");
Student s5=new Student(2L,"李一鸣",16,"广州");
Student s6=new Student(1L,"张锋",13,"湛江");
List<Student> student=new ArrayList<Student>();
student.add(s1);
student.add(s7);
student.add(s8);
student.add(s2);
student.add(s3);
student.add(s4);
student.add(s5);
student.add(s6);
boolean anyMatch = student.stream().anyMatch(s->"湖北".equals(s.getAddress()));
if (anyMatch) {
System.out.println("有湖北人");
}
boolean allMatch = student.stream().allMatch(s->s.getAge()>=15);
if (allMatch) {
System.out.println("所有学生都满15周岁");
}
boolean noneMatch = student.stream().noneMatch(s->"杨洋".equals(s.getName()));
if (noneMatch) {
System.out.println("没有叫杨洋的人");
}
}
更多资源和教程请关注公众号:非科班的科班。
如果觉得我写的还可以请给个赞,谢谢大家,你的鼓励是我创作的动力
以上是关于Java8 Stream用法详解的主要内容,如果未能解决你的问题,请参考以下文章