• day41 jdk8新特性Stream流 数据库安装


    流(Stream)中保存了对集合或者数组数据的操作,和集合类似,但是集合中保存的是数据。Stream不能保存数据

    一、创建流

    • 通过Collection对象的stream()或者parallelStream()

    • 通过Arrays类的stream(Array[])方法

    • 通过Stream接口of() iterate() generate()方法

    • 通过 IntStream, LongStream, DoubleStream接口中的of(), range(), rangeClosed()方法

     //1. 通过Collection对象的stream()或者parallelStream()
            List list = new ArrayList<>();

      Stream stringStream = list.parallelStream();

     //2.通过Arrays类的stream()方法
            String[] names = {"乔峰", "虚竹", "段誉", "阿朱", "段正淳", "萧远山"};
            Stream stream = Arrays.stream(names);

    //3.通过Stream接口of()   iterate()   generate()方法
       //     System.out.println("-----------通过Stream接口的of()--------");
            Stream integerStream = Stream.of(10, 20, 30, 40, 50, 60); 

              Stream iterate = Stream.iterate(0, x -> x + 2);

            Stream generate = Stream.generate(() -> new Random().nextInt(100));

     //4.1.  通过 IntStream,  LongStream, DoubleStream接口中的of(), range(), rangeClosed()方法
            IntStream intStream = IntStream.of(10, 20, 30, 40, 50, 60, 70, 80); 

    二、流的操作  

    一个stream调用方法变成一个新的stream

    • filter(): 对元素数据进行过滤

    • limit(): 限制数据

    • skip(): 跳过几个元素

    • distinct(): 去重

    • sorted() 排序

    • map() 把流映射到另外一组数据

    • parallel() (parallelStream) 获取一个并行流

      1. public class StreamDemo2 {
      2. public static void main(String[] args) {
      3. List list = new ArrayList<>();
      4. list.add(new Employee("张无忌", 12000.0));
      5. list.add(new Employee("小昭", 18000.0));
      6. list.add(new Employee("张三丰", 32000.0));
      7. list.add(new Employee("金花婆婆", 15000.0));
      8. list.add(new Employee("宋青书", 8000.0));
      9. list.add(new Employee("灭绝师太", 13000.0));
      10. list.add(new Employee("谢逊", 27000.0));
      11. list.add(new Employee("成昆", 12800.0));
      12. list.add(new Employee("殷天正", 32000.0));
      13. list.add(new Employee("殷素素", 14500.0));
      14. list.add(new Employee("张翠山", 16900.0));
      15. list.add(new Employee("张松溪", 14200.0));
      16. list.add(new Employee("灭绝师太", 13000.0));
      17. list.add(new Employee("灭绝师太", 13000.0));
      18. list.add(new Employee("灭绝师太", 13000.0));
      19. list.add(new Employee("灭绝师太", 13000.0));
      20. list.add(new Employee("灭绝师太", 13000.0));
      21. // 1. filter 过滤 过滤出工资大于15000的员工
      22. Stream employeeStream = list.stream().filter(e -> e.getSalary() > 15000);
      23. // employeeStream.forEach(System.out::println);
      24. //2. limit 限制数据 取集合中的前两条数据
      25. Stream limit = list.stream().limit(2);
      26. // limit.forEach(System.out::println);
      27. //3. skip 跳过几条数据
      28. Stream skip = list.stream().skip(3);
      29. // skip.forEach(System.out::println);
      30. //4. distinct 去重 , 集合中的元素需要重写equals方法
      31. //list.stream().distinct().forEach(System.out::println);
      32. //5.sorted 排序
      33. //list.stream().distinct().sorted((o1,o2)-> Double.compare(o1.getSalary(),o2.getSalary())).forEach(System.out::println);
      34. //6. map 把流映射到另外一组数据, 提取集合中员工的名字
      35. list.stream().map(e->e.getName()).forEach(System.out::println);
      36. //parallel (parallelStream) 获取一个并行流 采用多线程提高效率
      37. list.stream().parallel().map(e->e.getName()).forEach(System.out::println);
      38. //练习: 找出所有姓张的,按照工资升序排序
      39. // list.stream().filter(e->e.getName().startsWith("张")).sorted((o1,o2)->Double.compare(o1.getSalary(),o2.getSalary()))
      40. // .forEach(System.out::println);
      41. //练习2: 找出工资最低的张姓人员
      42. // list.stream().filter(e->e.getName().startsWith("张"))
      43. // .sorted((o1,o2)-> Double.compare(o1.getSalary(),o2.getSalary()))
      44. // .limit(1).forEach(System.out::println);
      45. //
      46. }
      47. }

    三、终止流

    • forEach() 遍历

    • min() 最小值

    • max() 最大值

    • count() 总数

    • reduce() 规约

    • collect() 收集

      1. public class StreamDemo4 {
      2. public static void main(String[] args) {
      3. List list = new ArrayList<>();
      4. list.add(new Employee("张无忌", 12000.0));
      5. list.add(new Employee("小昭", 18000.0));
      6. list.add(new Employee("张三丰", 32000.0));
      7. list.add(new Employee("金花婆婆", 15000.0));
      8. list.add(new Employee("宋青书", 8000.0));
      9. list.add(new Employee("灭绝师太", 13000.0));
      10. list.add(new Employee("谢逊", 27000.0));
      11. list.add(new Employee("成昆", 12800.0));
      12. list.add(new Employee("殷天正", 32000.0));
      13. list.add(new Employee("殷素素", 14500.0));
      14. list.add(new Employee("张翠山", 16900.0));
      15. list.add(new Employee("张松溪", 14200.0));
      16. //forEach()
      17. // list.stream().filter(e-> e.getName().startsWith("张")).forEach(System.out::println);
      18. // min() max()
      19. //找出工资最低的张姓人员
      20. Optional min = list.stream().filter(e -> e.getName().startsWith("张"))
      21. .min((o1, o2) -> Double.compare(o1.getSalary(), o2.getSalary()));
      22. System.out.println(min.get());
      23. //找出工资最高的员工
      24. Optional max = list.stream().max((o1, o2) -> Double.compare(o1.getSalary(), o2.getSalary()));
      25. System.out.println(max.get());
      26. //count() 求总数 输出员工总数
      27. long count = list.stream().count();
      28. System.out.println("员工总数:" + count);
      29. System.out.println(list.size());
      30. //reduce() 规约 输入数据后对数据产生某些影响 对数据进行深加工,在Stream中此方法主要用于数据的叠加
      31. //求公司员工工资总和
      32. Optional reduce = list.stream().map(e -> e.getSalary()).reduce((x, y) -> x + y);
      33. System.out.println(reduce.get());
      34. int[] array = {1,2,3,4,5,6,7,8,9,10};
      35. OptionalInt reduce1 = Arrays.stream(array).reduce((x, y) -> x + y);
      36. System.out.println(reduce1.getAsInt());
      37. String[] arr = {"a","b","c","d","e"};
      38. Optional reduce2 = Arrays.stream(arr).reduce((x, y) -> x + y);
      39. System.out.println(reduce2.get());
      40. //collect 收集
      41. // 收集所有员工的姓名,收集到一个集合中
      42. List collect = list.stream().map(e -> e.getName()).collect(Collectors.toList());
      43. //collect.forEach(System.out::println);
      44. Iterator iterator = collect.iterator();
      45. while(iterator.hasNext()){
      46. String str = iterator.next();
      47. System.out.println(str);
      48. }
      49. }
      50. }

      四、新时间API

    • 之前的API存在的问题: 线程安全问题,设计混乱

    • 本地化的日期对象

      • LocalDate

      • LocalTime

      • LocalDateTime

      • Instant 时间戳

      • ZXoneld 时区

      • DateTimeFormatter 日期格式转换

    • SimpleDateFormat的线程安全问题

      1. public static void main(String[] args) throws ExecutionException, InterruptedException {
      2. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      3. ExecutorService executorService = Executors.newFixedThreadPool(10);
      4. Callable callable = new Callable() {
      5. @Override
      6. public Date call() throws Exception {
      7. return simpleDateFormat.parse("2023-09-16 12:11:11");
      8. }
      9. };
      10. List> list = new ArrayList<>();
      11. for (int i = 0; i < 10; i++) {
      12. Future submit = executorService.submit(callable);
      13. list.add(submit);
      14. }
      15. for (Future dateFuture : list) {
      16. System.out.println(dateFuture.get());
      17. }
      18. executorService.shutdown();
      19. }
      1. /**
      2. * SimpleDateFormat的线程安全问题
      3. */
      4. public class DateTimeFormatterDemo {
      5. public static void main(String[] args) throws ExecutionException, InterruptedException {
      6. //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      7. DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
      8. ExecutorService pool = Executors.newFixedThreadPool(10);
      9. Callable callable = new Callable() {
      10. @Override
      11. public LocalDate call() throws Exception {
      12. return LocalDate.parse("2023-09-15");
      13. }
      14. };
      15. List> list = new ArrayList<>();
      16. for (int i = 0; i < 10; i++) {
      17. Future submit = pool.submit(callable);
      18. list.add(submit);
      19. }
      20. for (Future dateFuture : list) {
      21. System.out.println(dateFuture.get());
      22. }
      23. pool.shutdown();
      24. }
      25. }

  • 相关阅读:
    基于springboot实现车辆充电桩平台管理系统项目【项目源码+论文说明】计算机毕业设计
    spring boot 中使用minio
    被斯坦福抄作业了?在线体验下:国产大模型确实越来越棒啦!
    c++ Mixin实现的一种方法
    https服务部署指南
    Argo Rollouts结合Service进行Blue-Green部署
    聚合数据以科技赋能数字化转型,提升金融服务质效
    1.4.17 实验17:ASBR
    Python函数每日一讲4 - 一文让你彻底明白hasattr函数的使用
    前端框架EXT.NET Dotnet 3.5开发的实验室信息管理系统(LIMS)成品源码 B/S架构
  • 原文地址:https://blog.csdn.net/weixin_45939821/article/details/132913412