JDK8新特性---stream流
项目上用到了stream流,找篇blog,转载一下,介绍下Stream流的用法。
1 流概述
流是 JDK8 新增的成员,允许以声明性方式处理数据集合,可以把 Stream 流看作是遍历数据集合的一个高级迭代器
使用流的好处: 代码以声明性方式书写:说明想要完成什么,而不是说明如何完 成一个操作 可以把几个基础操作连接起来,来表达复杂的数据处理的流水 线,同时保持代码清晰可读
流是什么?
从支持数据处理操作的源生成元素序列.数据源可以是集合,数组 或 IO 资源
从操作角度来看,流与集合是不同的. 流不存储数据值; 流的目的 是处理数据,它是关于算法与计算的. 如果把集合作为流的数据源,创建流时不会导致数据流动; 如果流 的终止操作需要值时,流会从集合中获取值; 流只使用一次 流中心思想是延迟计算,流直到需要时才计算值

流使用时一般包括三件事:
1) 一个数据源(如集合)来执行一个查询;
2) 一个中间操作链,形成一条流的流水线
3) 一个终端操作,执行流水线,生成结果
2 Stream流的几种获得方式
public class Test01 {
public static void main(String[] args) {
//1 如何获得流,可以通过 Collection 集合,数据, 根据字面量获得流
// 1.1 通过 Collection 获得流
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "hello", "jj", "dd", "mm", "test");
Stream<String> stream1 = list.stream();
System.out.println(stream1);
stream1.forEach(System.out::println);
// 1.2 根据数组获得流
String[]data = {"zhangsan","lisi","wangwu"};
Stream<String> stream2 = Arrays.stream(data);
stream2.forEach(s -> System.out.print(s + " "));
System.out.println();
// 1.3 直接通过值获得流
Stream<String> stream3 = Stream.of("1", "2", "3", "4");
stream3.forEach(s -> System.out.print(s + " "));
System.out.println();
// 1.4 无限流
Stream.iterate(100, x -> x + 3).limit(10).forEach(s -> System.out.print(s + " "));
System.out.println();
}
}
3 Stream流的筛选操作
public class Test01 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "aa", "cc", "d","bb");
Stream<String> stream = list.stream();
//流的筛选与切片
//去重:distinct()
stream.distinct().forEach(System.out::println);
System.out.println("-------------1-----------");
//过滤filter(Predicate<? super T> predicate); 传递一个Predicate接口
// stream.filter(x -> x.length()>2).forEach(System.out::println);
//java.lang.IllegalStateException: 流只能使用一次
list.stream().filter(x -> x.length() > 2).forEach(System.out::println);
System.out.println("-------------2-----------");
//sorted()排序操作 Comparator<? super T> comparator 传递一个Comparator接口
list.stream().sorted(String::compareTo).forEach(System.out::println);
System.out.println("-------------3-----------");
//limt()截断操作
list.stream().limit(5).forEach(System.out::println);
System.out.println("--------------4----------");
//skip()跳过
list.stream().skip(3).forEach(System.out::println);
System.out.println("---------------5---------");
}
}
4 Stream流的map映射
public class Test02 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "aa", "bb", "cc", "d", "eeeeee");
//map(Function<? super T, ? extends R> mapper); 传递一个Function接口
//为每个元素应用toUpperCase()把小写转换为大写
list.stream().map(String::toUpperCase).forEach(System.out::println);
//list每个每个元素的长度,然后拼接空格 2 2 2 2 1 6
list.stream().map(String::length).map(len->len + " ").forEach(System.out::println);
System.out.println("----------2-------");
//转换为数值流
List<Integer> integerList= Arrays.asList(54,1,78,90,345);
IntStream intStream = integerList.stream().mapToInt(x->x);
intStream.forEach(x->System.out.print(x+" "));
}
}
5 Stream流的查找与匹配
public class Test03 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "aa", "bb", "cc", "d", "eeeeee", "sssssss");
//allMatch()判断流中所有的元素是否都匹配给定的谓词
System.out.println(list.stream().allMatch(s -> s.length() > 3)); //false
//anyMatch()判断流中是否有某个元素可以匹配指定的谓词
System.out.println(list.stream().anyMatch(s -> s.equals("wkcto"))); //true
//noneMathc()判断流中的元素是否都没有匹配指定谓词的
System.out.println(list.stream().noneMatch(s -> s.equals("jj"))); //false
//findAny()和findFirst()的返回值类型均为Optional<T>
//查找任意一个
System.out.println(list.stream().filter(s -> s.length() > 5).findAny().get());
//查找第一个
try {
System.out.println(list.stream().filter(s -> s.length() > 20).findFirst().get());
}catch (Exception e) {
e.printStackTrace();
}
//查找第一个,如果不加orElse 会输出Optional.empty
System.out.println(list.stream().filter(s -> s.length() > 20).findFirst().orElse("不存在"));
}
}
6 Stream流的reduce规约
public class Test04 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "aa", "bb", "cc", "d", "eeeeee", "sssssss");
//1 forEach 遍历
list.stream().forEach(System.out::println);
//2 cout 统计
System.out.println(list.stream().filter(x -> x.length() > 2).count());
//3 reduce 归纳合并
//传递的是BinaryOperator<T> accumulator 接口
Optional<String> reduce = list.stream().reduce((s1, s2) -> s1 + "--" + s2);
System.out.println(reduce.get());
//传递Consumer<? super T> consumer 接口
reduce.ifPresent(System.out::println);
//4数值操作
List<Integer> list2 = Arrays.asList(6, 21, 87, 34, 1, 78, 54);
//5求和,指定初始值
//reduce(T identity, BinaryOperator<T> accumulator);
System.out.println(list2.stream().reduce(0, Integer::sum));
//求和,没有初始值
//Optional<T> reduce(BinaryOperator<T> accumulator);
System.out.println(list2.stream().reduce((x, y) -> x + y).orElse(0));
//6最值
//Optional<T> reduce(BinaryOperator<T> accumulator);
System.out.println(list2.stream().reduce(Math::max).get());
System.out.println(list2.stream().reduce(Math::min).get());
}
7 Stream流映射到数值流
public class Test05 {
public static void main(String[] args) {
List<Integer> list2 = Arrays.asList(6, 21, 87, 34, 1, 78, 54);
//求和 IntStream mapToInt(ToIntFunction<? super T> mapper);
System.out.println(list2.stream().mapToInt(x->x).sum() );
//最大值 OptionalInt max();
//public int getAsInt() {
// if (!isPresent) {
// throw new NoSuchElementException("No value present");
// }
// return value;
// }
System.out.println(list2.stream().mapToInt(x->x).max().getAsInt() );
//最小值 OptionalInt min();
//public int orElse(int other) {
// return isPresent ? value : other;
//}
System.out.println(list2.stream().mapToInt(x->x).min().orElse(0) );
//平均值
//DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
//OptionalDouble average();
System.out.println(list2.stream().mapToDouble(x->x).average().getAsDouble());
//求最大值
System.out.println(list2.stream().max(Integer::compareTo).get());
//求最小值
list2.stream().min(Integer::compareTo).ifPresent(System.out::println);
}
}
8 Stream流的collect规约
public class Test06 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "ss", "aa", "hello", "jj","hello","xx", "good");
//把 stream 流转换为集合
Set<String> stringSet = list.stream().collect(Collectors.toSet());
System.out.println( stringSet );
//把 Stream 流转换为数组
Object[] objects = list.stream().toArray();
System.out.println( Arrays.toString(objects));
String[] toArray = list.stream().toArray(String[]::new);
System.out.println(Arrays.toString(toArray));
//Stream 流转换为字符串
String collect = list.stream().collect(Collectors.joining(","));
System.out.println(collect);
}
}
————————————————
版权声明:本文为CSDN博主「ChengZi~」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38339124/article/details/93423360
JDK8新特性---stream流的更多相关文章
- 这可能是史上最好的 Java8 新特性 Stream 流教程
本文翻译自 https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ 作者: @Winterbe 欢迎关注个人微信公众 ...
- JDK8新特性(二) 流式编程Stream
流式编程是1.8中的新特性,基于常用的四种函数式接口以及Lambda表达式对集合类数据进行类似流水线一般的操作 流式编程分为大概三个步骤:获取流 → 操作流 → 返回操作结果 流的获取方式 这里先了解 ...
- jdk8新特性-stream
一.什么是流stream 1.可理解为高级版本的 Iterator 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的. 2.单向,不可往复 数据只能遍历一次,遍历过一次后即用尽了,就好比 ...
- Java1.8新特性 - Stream流式算法
一. 流式处理简介 在我接触到java8流式数据处理的时候,我的第一感觉是流式处理让集合操作变得简洁了许多,通常我们需要多行代码才能完成的操作,借助于流式处理可以在一行中实现.比如我们希望对一个包 ...
- 再来看看Java的新特性——Stream流
半年前开始试着使用Java的新特性,给我印象最深的就是Stream流和Optional.其中Stream提高了看法效率,让代码看起来十分清爽. 为什么要使用流? 摘要中已经说明了,为了提高开发效率.流 ...
- Java8新特性 Stream流式思想(一)
遍历及过滤集合中的元素使用传统方式遍历及过滤集合中的元素package cn.com.zq.demo01.Stream.test01.Stream; import java.util.ArrayLis ...
- Java8新特性 Stream流式思想(二)
如何获取Stream流刚开始写博客,有一些不到位的地方,还请各位论坛大佬见谅,谢谢! package cn.com.zq.demo01.Stream.test01.Stream; import org ...
- java8 新特性Stream流的应用
作为一个合格的程序员,如何让代码更简洁明了,提升编码速度尼. 今天跟着我一起来学习下java 8 stream 流的应用吧. 废话不多说,直入正题. 考虑以下业务场景,有四个人员信息,我们需要根据性 ...
- Java8新特性Stream流应用示例
Java8新特性介绍 过滤集合 List<String> newList = list.stream().filter(item -> item != null).collect(C ...
随机推荐
- 谈一谈php反序列化
1.序列化与反序列化 php中有两个函数serialize()和unserialize() 序列化serialize(): 当在php中创建了一个对象后,可以通过serialize()把这个对象转变成 ...
- 内网hash传递
前言: 我们在平常打点的时候,遇到有内网或者有域的环境的时候,我们只获得了内网中的一台机子的shell,由这台机子我们可以获得这台机子所在的网段的相关其他主机.比如说有域的时候的域控机,有多层内网的堡 ...
- 使用javacv 截取视频指定帧节
个人博客 地址:https://www.wenhaofan.com/article/20190407105818 引入依赖 <dependency> <groupId>org. ...
- 在Java后端如何添加拦截器
在安全编码规范中,在Java后端controller层接口需要对调用者的身份进行确认,以防非法用户进行访问.若是在controller层的每个接口处都添加逻辑判断,那么代码重复度高,并且费力费时.此时 ...
- 518-零钱兑换 II(完全背包-求方案总数)
518-零钱兑换 II(完全背包-求方案总数) 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 示例 1: 输入: amount = 5, c ...
- Leetcode Week1 Regular Expression Matching
Question Given an input string (s) and a pattern (p), implement regular expression matching with sup ...
- Apache服务:使用 Apache 服务部署静态网站
1.安装Apache服务 第一步:安装Apache服务程序 yum install httpd 具体流程参考https://www.cnblogs.com/python-wen/p/1016845 ...
- Vue组件中的Data为什么是函数。
简单点说,组件是要复用的,在很多地方都会调用. 如果data不是函数,而是属性,就又可能会发生多个地方的相同组件操作同一个Data属性,导致数据混乱. 而如果是函数,因为组件data函数的返回值是 ...
- python UI自动化之js操作
js处理iframe无需先切换到iframe上,再切回来操作.它可以在iframe上和主页面上来回自由操作. switch方法需要先切换到iframe上,操作完之后又的切换回来(很容易忘记切换回来), ...
- VS 2017 mscorlib.dll 加载元数据时发生严重错误,需要终止调试
VS 2017 mscorlib.dll 加载元数据时发生严重错误,需要终止调试 C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0. ...