项目上用到了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流的更多相关文章

  1. 这可能是史上最好的 Java8 新特性 Stream 流教程

    本文翻译自 https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ 作者: @Winterbe 欢迎关注个人微信公众 ...

  2. JDK8新特性(二) 流式编程Stream

    流式编程是1.8中的新特性,基于常用的四种函数式接口以及Lambda表达式对集合类数据进行类似流水线一般的操作 流式编程分为大概三个步骤:获取流 → 操作流 → 返回操作结果 流的获取方式 这里先了解 ...

  3. jdk8新特性-stream

    一.什么是流stream 1.可理解为高级版本的 Iterator 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的. 2.单向,不可往复 数据只能遍历一次,遍历过一次后即用尽了,就好比 ...

  4. Java1.8新特性 - Stream流式算法

    一. 流式处理简介   在我接触到java8流式数据处理的时候,我的第一感觉是流式处理让集合操作变得简洁了许多,通常我们需要多行代码才能完成的操作,借助于流式处理可以在一行中实现.比如我们希望对一个包 ...

  5. 再来看看Java的新特性——Stream流

    半年前开始试着使用Java的新特性,给我印象最深的就是Stream流和Optional.其中Stream提高了看法效率,让代码看起来十分清爽. 为什么要使用流? 摘要中已经说明了,为了提高开发效率.流 ...

  6. Java8新特性 Stream流式思想(一)

    遍历及过滤集合中的元素使用传统方式遍历及过滤集合中的元素package cn.com.zq.demo01.Stream.test01.Stream; import java.util.ArrayLis ...

  7. Java8新特性 Stream流式思想(二)

    如何获取Stream流刚开始写博客,有一些不到位的地方,还请各位论坛大佬见谅,谢谢! package cn.com.zq.demo01.Stream.test01.Stream; import org ...

  8. java8 新特性Stream流的应用

    作为一个合格的程序员,如何让代码更简洁明了,提升编码速度尼. 今天跟着我一起来学习下java 8  stream 流的应用吧. 废话不多说,直入正题. 考虑以下业务场景,有四个人员信息,我们需要根据性 ...

  9. Java8新特性Stream流应用示例

    Java8新特性介绍 过滤集合 List<String> newList = list.stream().filter(item -> item != null).collect(C ...

随机推荐

  1. HDU 6417

    题意 英文 做法 \(S_{a,b}\)为\(a\)与\(b\)中素数次幂奇偶性不同的集合,容易得出\[d_{a,b}=\left\{\begin{aligned}1 &&|S_{a, ...

  2. hdu 1025 Constructing Roads In JGShining's Kingdom(最长上升子序列)

    题意:贫穷和富有的城市都按顺序1-n排列,需要在中间建造尽可能多的道路,最多可以建造多少条? 解:如果条件这样给出,贫穷的城市按顺序排列,并且按顺序给出每个贫穷城市需要的资源,那么能建造的最多的道路数 ...

  3. Python静态方法、类方法、属性方法

    静态方法 使用静态方法以后,相当于把下面的函数和类的关系截断了,它的作用相当于是类下面的一个独立函数,不会自动传入参数self. class people:..... @staticmethod de ...

  4. 安装oracle11gR2

    一.通过百度云等途径下载oracle11gR2 二.安装步骤 1,解压缩文件,将两个压缩文件一起解压. 2,在setup.exe右键--属性--兼容性,勾“以管理员身份运行此程序”. 3,双击“set ...

  5. Query的选择器

    Query的选择器   一. 基本选择器   1. ID选择器            ID选择器#id就是利用DOM元素的id属性值来筛选匹配的元素,并以iQuery包装集的形式返回给对象.      ...

  6. php实现简易留言板效果

    首先是Index页面效果图 index.php <?php header('content-type:text/html;charset=utf-8'); date_default_timezo ...

  7. Mac上利用VScode配置c/c++开发环境

    Mac上利用VScode配置c/c++开发环境 哭辽,Typora里面最好不要插入表情,不然保存会闪退 首先你要有一个vscode 在扩展里面下载c/c++ 第一步 ⬆+com+p 打开命令模式:选择 ...

  8. sap gui中打断点,进入不了断点

    1: 当abap development tool 打开时,会影响sap gui中的断点进入. 2: 需要sap gui和abap development tool  都关闭,重新进入sap gui打 ...

  9. eclipse unable to start within 45 seconds

    在eclipse4.8.2中运行tomcat8.5项目时,提示出错: Server Tomcat v8.0 Server at localhost was unable to start within ...

  10. DataGridView 定位到指定行

    //定位到指定行(样式)dataGridView1.ClearSelection();dataGridView1.Rows[selectIndex].Selected = true; //让指定行处于 ...