java8新特性 - Stream 的中间操作

Stream 的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上出发终止操作,否则中间操作不会执行任何的处理,而在终止操作时一次性全部处理,称为 “惰性求值”

筛选与切片

filter(Predicate p)

接收 lambda ,从流中排除某些元素

@Test
public void test1(){
    List<Student> students = Student.getStudents();
    // 查询年龄大于18岁的,最后的forEach(System.out::println);是终止操作,这里先不解释
    students.stream().filter(s -> s.getAge()>18).forEach(System.out::println);// 输出年龄大于18的student对象数据
}

limit(n)

截断流,使其元素不超过给定数量

@Test
public void test2(){
    List<Student> students = Student.getStudents();
    // 截取输出前两个数据,最后的forEach(System.out::println);是终止操作,这里先不解释
    students.stream().limit(2).forEach(System.out::println);
}

skip(n)

跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流(什么都不输出)

@Test
public void test3(){
    List<Student> students = Student.getStudents();
    // 跳过前两条数据,最后的forEach(System.out::println);是终止操作,这里先不解释
    students.stream().skip(2).forEach(System.out::println);
}

distinct()

筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

可以理解为,去重是根据一个对象中的所有属性进行对比,需要每个属性的值都一直才能进行去重

@Test
public void test4(){
    List<Student> students = Student.getStudents();
    // 去重,最后的forEach(System.out::println);是终止操作,这里先不解释
    students.stream().distinct().forEach(System.out::println);
}

映射

map(Function f) 常用

接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

@Test
public void test1(){
    List<String> list = Arrays.asList("aa", "bb", "cc");
    // 将字母转为大写
    list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);

    // 练习 :取出名字长度等于3的同学名字
    List<Student> students = Student.getStudents();
    Stream<String> names = students.stream().map(Student::getName);
    names.filter(name -> name.length() == 3).forEach(System.out::println);
}

mapToDouble(ToDoubleFunction f) :接收一个函数作为参数,该函数会被应用到每一个元素上,产生一个新的 DoubleStream

mapToInt(ToIntFunction f) :接收一个函数作为参数,该函数会被应用到每一个元素上,产生一个新的 IntStream

mapToLong(ToLongFunction f) :接收一个函数作为参数,该函数会被应用到每一个元素上,产生一个新的 LongStream

flatMap(Function f) :

接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所以流连成一个流

排序

sorted() : 产生一个新流,其中按照自然顺序排序

@Test
public void test2(){
    List<Integer> list = Arrays.asList(1,2,32,12,4,5,34,5,6,45,76);
    list.stream().sorted().forEach(System.out::println);
}

sorted(Comparator com) :产生一个新流,其中按照比较器中的规则排序

@Test
public void test3(){
    List<Student> students = Student.getStudents();
    students.stream().sorted((s1,s2)->s1.getAge()-s2.getAge()).forEach(System.out::println);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值