目录

通过stream获取集合中指定数据:

获取流:

stream流中的foreach方法:

stream流中的filter方法:

stream流中的limit方法:

stream流中的skip方法:

Stream流中的map方法:

stream流中的sorted方法:

Stream流中的distinct方法:

Stream流的match方法:

Stream流的find方法:

Stream流中的max和min方法:

Stream流的reduce方法:

Stream的concat方法:

Stream小练习:

将流中的数据收集到集合中:

将流中的数据收集到数组中:

对流中数据进行聚合运算:

对流中数据进行分组:

多级分组:

对流中数据进行拼接:

Optional类的基本使用:


参考:https://www.bilibili.com/video/BV1zJ411R7uQ/?vd_source=c75e68fd099206ad9761f2134ce79ce2

推荐博客:恕我直言,我怀疑你没怎么用过Stream流

我的是直接实战演示,大家想要知道概念什么的话可以参考一下上面的博客。

下面的内容写的可能比较混乱

通过stream获取集合中指定数据:

package com.jdktest01.day02;import java.util.ArrayList;
import java.util.Collections;/*** @author a1002*/
public class StreamTest01 {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张三丰", "师太", "韦小宝", "康熙");ArrayList<String> zhangList = new ArrayList<>();list.stream().filter((s) -> {return s.startsWith("张");}).filter((s) -> {return s.length() == 3;})//遍历.forEach((s) -> {System.out.println(s);System.out.println(s.length());//添加到集合中zhangList.add(s);});System.out.println("=========================");//拿到所有姓张的且长度为3的//集合遍历System.out.println(zhangList);System.out.println("---------------------------");list.forEach(System.out::println);}
}

获取流:

package com.jdktest01.day02;import java.util.*;
import java.util.stream.Stream;/*** @author a1002*/
public class StreamTest03 {public static void main(String[] args) {// 方式1 : 根据Collection获取流// Collection接口中有一个默认的方法: default Stream<E> stream()List<String> list = new ArrayList<>();Stream<String> stream1 = list.stream();Set<String> set = new HashSet<>();Stream<String> stream2 = set.stream();Map<String, String> map = new HashMap<>();Stream<String> stream3 = map.keySet().stream();Stream<String> stream4 = map.values().stream();Stream<Map.Entry<String, String>> stream5 = map.entrySet().stream();// 方式2 : Stream中的静态方法of获取流// static<T> Stream<T> of(T... values)Stream<String> stream6 = Stream.of("aa", "bb", "cc");String[] strs = {"aa", "bb", "cc"};Stream<String> stream7 = Stream.of(strs);// 基本数据类型的数组行不行?不行的,会将整个数组看做一个元素进行操作.int[] arr = {11, 22, 33};Stream<int[]> stream8 = Stream.of(arr);}
}

stream流中的foreach方法:

package com.jdktest01.day02;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;/*** @author a1002*/
public class StreamTest04 {public static void main(String[] args) {List<String> one = new ArrayList<>();Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");one.stream().forEach((String str) -> {System.out.println(str);});System.out.println("-------------------------");one.stream().forEach(System.out::println);System.out.println("-------------------------");one.forEach(System.out::println);}
}

stream流中的filter方法:

//过滤

List<String> one = new ArrayList<>();Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");one.stream().filter((String s) -> {return s.length() == 3;}).forEach(System.out::println);System.out.println("---------------------");//简化one.stream().filter(s -> s.length() == 3).forEach(System.out::println);System.out.println("---------------------");

stream流中的limit方法:

//限制输出数据数量

            one.stream().limit(3).forEach(System.out::println);

stream流中的skip方法:

List<String> one = new ArrayList<>();Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");//跳过指定的前两个数据one.stream().skip(2).forEach(System.out::println);

从下面可以看到skip指定类型是long,所以不能指定跳过某一个String。

 Stream流中的map方法:

@Testpublic void testMap() {//Map可以将一种类型的流转为另一种类型的流Stream<String> original = Stream.of("11", "22", "33");//将stream流中的字符串转为Integer//参数就是你原本的类型
//        original.map((String s) -> {
//            return Integer.parseInt(s);
//        });System.out.println("---------------------");//简化//      original.map(s -> Integer.parseInt(s)).forEach(System.out::println);//再简化original.map(Integer::parseInt).forEach(System.out::println);}

stream流中的sorted方法:

//排序

@Testpublic void testSorted() {// sorted(): 根据元素的自然顺序排序// sorted(Comparator<? super T> comparator): 根据比较器指定的规则排序Stream<Integer> stream = Stream.of(33, 22, 11, 55);//升序stream.sorted().forEach(System.out::println);System.out.println("------------------------");//降序stream.sorted((Integer i1, Integer i2) -> {return i2 - i1;}).forEach(System.out::println);System.out.println("------------------------");//降序简化stream.sorted((i1, i2) -> i2 - i1).forEach(System.out::println);}

Stream流中的distinct方法:

// distinct对自定义对象去除重复@Testpublic void testDistinct() {Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);stream.distinct().forEach(System.out::println);Stream<String> stream1 = Stream.of("a", "b", "c", "a", "b");stream1.distinct().forEach(System.out::println);}

对Person类中的equals和hashcode方法进行重写,stream中的数据再运行时就会被去重

@Testpublic void testDistinct01() {Stream<Person> stream = Stream.of(new Person("貂蝉", 18),new Person("杨玉环", 20),new Person("杨玉环", 20),new Person("西施", 16),new Person("西施", 16),new Person("王昭君", 25));stream.distinct().forEach(System.out::println);}

重写Person类中的equals和hashcode方法:

运行结果:

Stream流的match方法:

@Testpublic void testMatch() {Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);//allMatch需要所有的元素都满足才返回true//allMatch:匹配所有元素,所有的元素都需要满足条件boolean b = stream.allMatch((Integer i) -> {return i > 22;});System.out.println(b);Stream<Integer> stream1 = Stream.of(11, 2, 4, 5);//allMatch需要所有的元素都满足才返回trueboolean b1 = stream1.allMatch((Integer i) -> {return i > 0;});System.out.println(b1);//anyMatch: 匹配某个元素,只要有其中一个元素满足条件即可Stream<Integer> stream3 = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);boolean b2 = stream3.anyMatch((Integer i) -> {return i > 22;});System.out.println(b2);//noneMatch: 匹配所有元素,所有元素都不满足条件Stream<Integer> stream4 = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);boolean b3 = stream4.noneMatch(i -> i > 0);System.out.println(b3);}

Stream流的find方法:

@Testpublic void testFind() {Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);Optional<Integer> optional = stream.findFirst();System.out.println(optional.get());}

Stream流中的max和min方法:

@Testpublic void testMax() {//获取最大值Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);Optional<Integer> max = stream.max((o1, o2) -> o1 - o2);System.out.println(max.get());//获取最小值Optional<Integer> min = Stream.of(5, 6, 3, 1).min((o1, o2) -> o1 - o2);System.out.println(min.get());}

输出:

Stream流的reduce方法:

        // T reduce(T identity, BinaryOperator<T> accumulator);// T identity: 默认值// BinaryOperator<T> accumulator: 对数据进行处理的方式// reduce如何执行?// 第一次, 将默认值赋值给x, 取出集合第一元素赋值给y// 第二次, 将上一次返回的结果赋值x, 取出集合第二元素赋值给y// 第三次, 将上一次返回的结果赋值x, 取出集合第三元素赋值给y// 第四次, 将上一次返回的结果赋值x, 取出集合第四元素赋值给y//以此类推
@Testpublic void testReduce() {int reduce = Stream.of(4, 5, 7, 2, 9).reduce(0, (x, y) -> {System.out.println("x = " + x + " y = " + y);return x + y;});System.out.println(reduce);}

有点类似于js的特性。

27即为数据和。

找出最大值:

int max = Stream.of(4, 5, 7, 2, 9).reduce(0, (x, y) -> {return x > y ? x : y;});System.out.println(max);

对stream里面封装对象里的某一个数据进行求和:

@Testpublic void testReduce01() {Integer totalAge = Stream.of(new Person("刘德华", 58),new Person("张学友", 56),new Person("郭富城", 54),new Person("黎明", 52)).map((p) -> {return p.getAge();}).reduce(0, (x, y) -> {return x + y;});System.out.println("totalAge= " + totalAge);}

求stream内封装对象某一个属性最大值

Integer maxAge = Stream.of(new Person("刘德华", 58),new Person("张学友", 56),new Person("郭富城", 54),new Person("黎明", 52)).map(p -> p.getAge()).reduce(0, Math::max);System.out.println("maxAge=" + maxAge);

统计某一个元素出现的次数:

//统计a出现的次数Integer count = Stream.of("a", "b", "a", "d", "a").map(s -> {if (s == "a") {return 1;} else {return 0;}}).reduce(0, Integer::sum);System.out.println("count=" + count);

Stream的concat方法:

@Testpublic void testContact() {Stream<String> streamA = Stream.of("张三");Stream<String> streamB = Stream.of("李四");//合并成一个流Stream<String> newStream = Stream.concat(streamA, streamB);// 注意:合并流之后,不能操作之前的流啦.// streamA.forEach(System.out::println);newStream.forEach(System.out::println);}

Stream小练习:

public static void main(String[] args) {// 第一个队伍List<String> one = new ArrayList<>();Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子", "洪七公");// 第二个队伍List<String> two = new ArrayList<>();Collections.addAll(two, "古力娜扎", "张无忌", "张三丰", "赵丽颖", "张二狗", "张天爱", "张三");// 1.第一个队伍只要名字为3个字的成员姓名;System.out.println("1.第一个队伍只要名字为3个字的成员姓名-----------------------");one.stream().filter(s -> s.length() == 3).forEach(System.out::println);// 2.第一个队伍筛选之后只要前3个人;System.out.println("2.第一个队伍筛选之后只要前3个人-----------------------");one.stream().limit(3).forEach(System.out::println);// 3.第二个队伍只要姓张的成员姓名;System.out.println("3.第二个队伍只要姓张的成员姓名-----------------------");two.stream().filter(s -> s.startsWith("张")).forEach(System.out::println);// 4.第二个队伍筛选之后不要前2个人;System.out.println("4.第二个队伍筛选之后不要前2个人-----------------------");two.stream().skip(2).forEach(System.out::println);// 5.将两个队伍合并为一个队伍;System.out.println("5.将两个队伍合并为一个队伍-----------------------");Stream<String> newStream = Stream.concat(one.stream(), two.stream());newStream.forEach(System.out::println);// 6.根据姓名创建`Person`对象;// 7.打印整个队伍的Person对象信息。System.out.println("6.根据姓名创建`Person`对象-----------------------");System.out.println("7.打印整个队伍的Person对象信息-----------------------");Stream<String> StreamAB = Stream.concat(one.stream(), two.stream());StreamAB.map(Person::new).forEach(System.out::println);}

输出:

将流中的数据收集到集合中:

//将流中的数据收集到集合中@Testpublic void testStreamToCollection() {Stream<String> stream = Stream.of("aa", "bb", "cc", "aa");//将流中的数据收集到集合中//collection收集流中的数据到集合中
//        List<String> list = stream.collect(Collectors.toList());
//        System.out.println("list = " + list);//        Set<String> set = stream.collect(Collectors.toSet());
//        System.out.println("set = " + set);HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));System.out.println("hashset = " + hashSet);}

将流中的数据收集到数组中:

@Testpublic void testStreamToArray() {// 转成Object数组不方便// Object[] objects = stream.toArray();// for (Object o : objects) {//     System.out.println("o = " + o);// }// String[]Stream<String> stream = Stream.of("aa", "bb", "cc", "aa");String[] strings = stream.toArray(String[]::new);System.out.println("strings = " + Arrays.toString(strings) + ", 长度:" + strings.length);}

对流中数据进行聚合运算:

@Testpublic void testStreamToOther() {Stream<Student> studentStream = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));//获取最大值Optional<Student> max = studentStream.collect(Collectors.maxBy((s1, s2) -> s1.getSocre() - s2.getSocre()));System.out.println(max.get());List<Student> max1 = new ArrayList<>();Collections.addAll(max1, new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));Optional<Student> collect = max1.stream().collect(Collectors.maxBy((s1, s2) -> s1.getSocre() - s2.getSocre()));System.out.println(collect.get());//获取最小值Stream<Student> studentStream1 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));Optional<Student> min = studentStream1.collect(Collectors.maxBy((s1, s2) -> s2.getSocre() - s1.getSocre()));System.out.println(min.get());//求总和Stream<Student> studentStream2 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));Integer sum = studentStream2.collect(Collectors.summingInt(s -> s.getAge()));System.out.println("sum = " + sum);// 平均值Stream<Student> studentStream3 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));//       Double avg = studentStream3.collect(Collectors.averagingInt(s -> s.getSocre()));Double avg = studentStream3.collect(Collectors.averagingInt(Student::getSocre));System.out.println("平均值: " + avg);// 统计数量Stream<Student> studentStream4 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));Long count = studentStream4.collect(Collectors.counting());System.out.println("统计数量: " + count);}

输出:

对流中数据进行分组:

@Testpublic void testCollectors() {Stream<Student> studentStream5 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 77));Map<Integer, List<Student>> map = studentStream5.collect(Collectors.groupingBy((s) -> s.getAge()));map.forEach((k, v) -> {System.out.println(k + "::" + v);});}

输出:

@Testpublic void testCollectors01() {Stream<Student> studentStream5 = Stream.of(new Student("赵丽颖", 58, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 99),new Student("柳岩", 52, 56));Map<String, List<Student>> map = studentStream5.collect(Collectors.groupingBy((s) -> {if (s.getSocre() > 60) {return "及格";} else {return "不及格";}}));map.forEach((k, v) -> {System.out.println(k + "::" + v);});}

输出:

多级分组:

// 多级分组@Testpublic void testCustomGroup() {Stream<Student> studentStream = Stream.of(new Student("赵丽颖", 52, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 55),new Student("柳岩", 52, 33));// 先根据年龄分组,每组中在根据成绩分组// groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)Map<Integer, Map<String, List<Student>>> map = studentStream.collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy((s) -> {if (s.getSocre() > 60) {return "及格";} else {return "不及格";}})));// 遍历map.forEach((k, v) -> {System.out.println(k);// v还是一个map,再次遍历v.forEach((k2, v2) -> {System.out.println("\t" + k2 + " == " + v2);});});}

输出:

对流中数据进行拼接:

@Testpublic void testCollection01() {Stream<Student> studentStream = Stream.of(new Student("赵丽颖", 52, 95),new Student("杨颖", 56, 88),new Student("迪丽热巴", 56, 55),new Student("柳岩", 52, 33));// 根据一个字符串拼接: 赵丽颖__杨颖__迪丽热巴__柳岩//    String names = studentStream.map(Student::getName).collect(Collectors.joining("__"));String names = studentStream.map(Student::getName).collect(Collectors.joining("___", "+", "-"));System.out.println(names);}

输出:

Optional类的基本使用:

@Testpublic void test01() {// 1.创建Optional对象// of:只能传入一个具体值,不能传入null// ofNullable: 既可以传入具体值,也可以传入null// empty: 存入的是nullOptional<String> op1 = Optional.of("凤姐");// Optional<String> op1 = Optional.of(null);// Optional<String> op2 = Optional.ofNullable("如花");// Optional<String> op2 = Optional.ofNullable("如花");Optional<Object> op3 = Optional.empty();// 2.isPresent: 判断Optional中是否有具体值, 有值返回true,没有值返回false// boolean present = op1.isPresent();// System.out.println("present = " + present);// 3.get: 获取Optional中的值,如果有值就返回值具体值,没有值就报错// System.out.println(op3.get());if (op1.isPresent()) {System.out.println(op1.get());} else {System.out.println("没有值");}}
@Testpublic void test02() {// Optional<String> userNameO = Optional.of("凤姐");Optional<String> userNameO = Optional.empty();//name = 如花吗?//       Optional<String> userNameO = Optional.of(" ");//name =// orElse: 如果Optional中有值,就取出这个值,如果没有值就使用参数指定的值String name = userNameO.orElse("如花吗?");System.out.println("name = " + name);}
@Testpublic void test04() {Optional<String> userNameO = Optional.of("凤姐");// Optional<String> userNameO = Optional.empty();// 存在做的什么// ifPresent: 如果有值就调用参数/*userNameO.ifPresent(s -> {System.out.println("有值: " + s);});*/// ifPresentOrElse: 存在做的什么,不存在做点什么userNameO.ifPresentOrElse(s -> {System.out.println("有值: " + s);}, () -> {System.out.println("没有值");});}

就这些吧。

浅聊一下Stream流相关推荐

  1. 小白初窥VR世界的通行证?浅聊 PCVR 串流软件 Virtual Desktop - VR与串流篇 上

    什么是Virtual Desktop? Virtual Desktop (以下简称VD)是一款VR串流软件,其通过局域网低延迟.高质量的流式传输将PC端的界面同步到用户的VR头显中,给用户带来舒适且愉 ...

  2. java双层list扁平化,浅谈java8 stream flatMap流的扁平化操作

    概念: Steam 是Java8 提出的一个新概念,不是输入输出的 Stream 流,而是一种用函数式编程方式在集合类上进行复杂操作的工具.简而言之,是以内部迭代的方式处理集合数据的操作,内部迭代可以 ...

  3. 函数式编程(JAVA)——Stream流

    函数式编程(JAVA)--Stream流 概述 Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作.可以更方便的让我们对集合或数组操作. 下述 ...

  4. stream流对象的理解及使用

    我的理解:用stream流式处理数据,将数据用一个一个方法去 . (点,即调用) 得到新的数据结果,可以一步达成. 有多种方式生成 Stream Source: 从 Collection 和数组 Co ...

  5. Cuda Stream流 分析

    Cuda Stream流分析 Stream 一般来说,cuda c并行性表现在下面两个层面上: • Kernel level • Grid level Stream和event简介 Cuda stre ...

  6. CUDA 7 Stream流简化并发性

    CUDA 7 Stream流简化并发性 异构计算是指高效地使用系统中的所有处理器,包括 CPU 和 GPU .为此,应用程序必须在多个处理器上并发执行函数. CUDA 应用程序通过在 streams ...

  7. Java8中Stream流对集合操作

    java8中Stream流引入函数式编程思想,主要配合各种接口.lambda表达式.方法引用等方式,为集合的遍历.过滤.映射等提供非常"优雅"的操作方式. Student.java ...

  8. Java8 Stream流递归,几行代码搞定遍历树形结构

    欢迎关注方志朋的博客,回复"666"获面试宝典 可能平常会遇到一些需求,比如构建菜单,构建树形结构,数据库一般就使用父id来表示,为了降低数据库的查询压力,我们可以使用Java8中 ...

  9. 【Java8新特性】面试官问我:Java8中创建Stream流有哪几种方式?

    写在前面 先说点题外话:不少读者工作几年后,仍然在使用Java7之前版本的方法,对于Java8版本的新特性,甚至是Java7的新特性几乎没有接触过.真心想对这些读者说:你真的需要了解下Java8甚至以 ...

  10. 10.Stream流

    一.Stream流 1.案例实现 按照下面的要求完成集合的创建和遍历 创建一个集合,存储多个字符串元素 把集合中所有以"张"开头的元素存储到一个新的集合 把"张" ...

最新文章

  1. 2.14 向量化 Logistic 回归的梯度输出-深度学习-Stanford吴恩达教授
  2. Redis进阶-布隆过滤器
  3. Qt学习(三):事件、定时器、事件过滤器
  4. 信息安全系统设计基础第八周学习总结
  5. python中start用法_Start Python 学习笔记(琐碎知识,持续更新。。。)
  6. JBoss BPM Travel Agency演示与现代BPM数据集成
  7. python 怎么处理json_Python是怎样处理json模块的
  8. Ubuntu 下 libev编译安装
  9. java实现rabbitmq动态路由/话题模型(topic queues), 生产者 消费者 交换机 消息队列
  10. Java基础面试题:AQS组件总结
  11. Palindrome - URAL - 1297(求回文串)
  12. CSS Reset Modern CSS Reset
  13. 人工神经网络编程内容,神经网络用什么编程
  14. 动态规划和分治法解合唱队形问题
  15. mysql 乐观锁 超卖_秒杀系统之一:防止超卖(乐观锁)
  16. 那些年微信开发过的鸡肋功能,及其带给我们的思考
  17. 50个ospf经典问题
  18. 【WebLogic】解决opatch执行报错“Exception occured: fuser could not be located”
  19. 计算机添加本地安全组用户名和密码错误,u租号总是密码错误-共享用户名和密码正确总提示错误...
  20. Ubuntu升级glibc库

热门文章

  1. 中小企业如何成功转型跨境电商
  2. PTA L1-087 机工士姆斯塔迪奥 C语言
  3. 好奇心日报产品分析报告
  4. 白糖期货上涨可能带动的股票
  5. Codeforces Round #465 (Div. 2) D. Fafa and Ancient Alphabet
  6. 可以救命的地震预警你开了吗?
  7. Altium Designer 安装教程【软件包+汉化版】
  8. 基于Agera的EventBus实现库
  9. SAT作文评分关键在于主题表达
  10. 语雀文章搬到CSDN并发布