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 ...
随机推荐
- CF1093E Intersection of Permutations [分块 +bitset]
大家好, 我非常喜欢暴力数据结构, 于是就用分块A了此题 分块题,考虑前缀和 \(b_i\) 表示 bitset 即 \(0\) ~ $i $ 出现过的数字,然后考虑直接暴力复制块然后前缀和,修改也很 ...
- 安装Docker到Ubuntu(APT)
运行环境 系统版本:Ubuntu 16.04.5 LTS 软件版本:Docker-CE-18.09.5 硬件配置:无 安装过程 1.卸载旧版本 root@ubuntu:~# sudo apt-get ...
- Winform递归绑定树节点
/// <summary> /// 绑定树节点 /// </summary> /// <param name="pid"></param& ...
- SQL Server 疑难杂症--转换科学计数法的数值字符串为decimal类型
今天在操作数据库时,需要将字符串转换成Decimal类型.代码如下: select cast('0.12' as decimal(18,2)); select convert(decimal(18,2 ...
- 机器学习笔记(十一)OCR技术的应用
1.介绍OCR: OCR(Photo optical character recognition 照片光学字符识别) 应用于读取电子照片中的文字. 2.算法思路: ① 识别文字区域: ② 字符切分: ...
- Yaf自定义autoload以实现Model文件和Controller文件命名区分
先上图: 由于Yaf作者在设计Yaf框架目录时没有直接区分开models文件和controllers文件,所以在IDE看着会很难受,眼睛离开了编辑器就不大好区分这两个文件夹的文件.所以自己写了一个au ...
- php Allowed memory size of 134217728 bytes exhausted
报错:PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in ...
- STL初学
标准模板库STL初学 线性数据结构 vector 一维向量,相当于数组 list 链表 map 映射,提供(Key,Value)式操作,相当于哈希表 string char字符串 queue 队列,先 ...
- 巨杉Tech | 十分钟快速搭建 Wordpress 博客系统
介绍 很多互联网应用程序开发人员第一个接触到的网站项目就是博客系统.而全球使用最广的Wordpress常常被用户用来快速搭建个人博客网站.默认情况下,Wordpress一般在后台使用MySQL关系型数 ...
- C++-POJ2777-Count Color[线段树][lazy标记][区间修改]
分析:https://www.bilibili.com/read/cv4777102 #include <cstdio> #include <algorithm> using ...