JDK8新特性-Stream流[通俗易懂]

JDK8新特性-Stream流[通俗易懂]JDK8新特性-Stream流,本教程附有非常多的例子,看完肯定能懂Stream流!

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

个人简介

作者是一个来自河源的大三在校生,以下笔记都是作者自学之路的一些浅薄经验,如有错误请指正,将来会不断的完善笔记,帮助更多的Java爱好者入门。

JDK8新特性-Stream流

教程概述

  • 本教程附有非常多的例子,看完肯定能懂Stream流!
  • 看完本教程,对于Stream api基本的使用完全没有问题,底层原理则不会深究!
  • 本教程借鉴过很多其他大佬的教程,并进行总结创新,难免会有相同之处。

Stream流的创建

用集合创建流

	  //创建普通顺序流
      Stream<Integer> stream = asList.stream();

      //创建并行流
      Stream<Integer> parallelStream = asList.parallelStream();

用数组创建流

	  int arr[]={ 
   1,2,3,4,5};
      IntStream intStream = Arrays.stream(arr);

使用Stream的静态方法创建流

Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);

顺序流转换成并行流

	  List<Integer> asList = Arrays.asList(1, 2, 3, 4, 5);
      //创建顺序流
      Stream<Integer> integerStream = asList.stream();
      //把顺序流转换成并行流
      Stream<Integer> parallel = integerStream.parallel();

实体类Person:

class Person { 
   
    private String name;  // 姓名
    private double salary; // 薪资
    private int age; // 年龄

    public Person(String name, double salary, int age) { 
   
        this.name = name;
        this.salary = salary;
        this.age = age;
    }

    public String getName() { 
   
        return name;
    }

    public void setName(String name) { 
   
        this.name = name;
    }

    public double getSalary() { 
   
        return salary;
    }

    public void setSalary(double salary) { 
   
        this.salary = salary;
    }

    public int getAge() { 
   
        return age;
    }

    public void setAge(int age) { 
   
        this.age = age;
    }

    @Override
    public String toString() { 
   
        return "Person{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", age=" + age +
                '}';
    }
}

流的遍历和查找元素(forEach、find)

遍历Stream顺序流

	  List<Person> list=new ArrayList<>();

      list.add(new Person("z1",2000.0,18));
      list.add(new Person("z2",3200.0,15));
      list.add(new Person("z3",1500.0,27));
      list.add(new Person("z4",7000.0,36));
      list.add(new Person("z5",5000.0,22));
      list.add(new Person("z6",4200.0,42));	  
	  //创建Stream顺序流
      Stream<Person> stream = list.stream();
      //遍历Stream顺序流
      stream.forEach(System.out::println);

遍历并行流(多线程,输出顺序会不一样)

	  //创建并行流(多线程)
      Stream<Person> parallelStream = list.parallelStream();
	  //遍历并行流(多线程,输出顺序会不一样)
	  parallelStream.forEach(System.out::println);

找出流中第一个元素

	  Optional<Person> first = stream.findFirst();
      System.out.println(first.get());

流的筛选(filter)

案例1:集合中大于5的元素,并打印出来

	  List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

      Stream<Integer> stream = list.stream();

      //1:集合中大于5的元素,并打印出来
      stream.filter(el->el>5).forEach(System.out::println);

案例2:筛选年龄大于25岁的人,并形成一个只有name的新的集合

	  List<Person> personList = new ArrayList<Person>();
      personList.add(new Person("z1",2000.0,18));
      personList.add(new Person("z2",3200.0,15));
      personList.add(new Person("z3",1500.0,27));
      personList.add(new Person("z4",7000.0,36));
      personList.add(new Person("z5",5000.0,22));
      personList.add(new Person("z6",4200.0,42));

      Stream<Person> personStream = personList.stream();

      List<String> collect = personStream
              .filter(person -> person.getAge() > 25)
          	  //只筛选出name,如果直接collect则返回的是person对象
              .map(Person::getName) 
              .collect(Collectors.toList());
      collect.forEach(System.out::println);

聚合(max、min、count)

案例3:获取String集合中最长的元素

	 List<String> list1 = Arrays.asList("qdiq", "sdji", "aaa", "ihduxdswaa", "qwer");

      Stream<String> stream1 = list1.stream();

      Optional<String> maxString = stream1.max(Comparator.comparing(String::length));
      System.out.println("maxString="+maxString.get());

案例4:比较集合中数字最大的并输出

	  List<Integer> integerList = Arrays.asList(20, 10, 30, 52, 42, 15, 11, 13, 19, 30);

      Stream<Integer> integerStream = integerList.stream();

      Optional<Integer> optionalInteger = integerStream.max(Comparator.comparing(Integer::intValue));
      System.out.println(optionalInteger.get());

案例5:计算Integer集合中大于6的元素的个数

	  List<Integer> list2 = Arrays.asList(7, 6, 4, 8, 2, 11, 9);
      long count = list2.stream().filter(integer -> integer > 6).count();
      System.out.println("集合中大于6的个数="+count);

映射(map)

  • 可以直接操作每一个流的元素
  • 凡是需要操作流中元素的都用map,filter只是起到筛选的作用

案例6:英文字符串数组的元素全部改为大写

	  Stream<String> stream = Arrays.stream(strArr);

      //s就是每一个元素
      List<String> collect = stream.map(s -> s.toUpperCase()).collect(Collectors.toList());

      collect.forEach(System.out::println);

案例7:整数数组每个元素+3

	  List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);

      Stream<Integer> stream1 = intList.stream();
      stream1.map(integer -> integer+=3).collect(Collectors.toList()).forEach(System.out::println);

案例8:将员工的薪资全部增加1000

	  List<Person> personList = new ArrayList<Person>();
      personList.add(new Person("z1",2000.0,18));
      personList.add(new Person("z2",3200.0,15));
      personList.add(new Person("z3",1500.0,27));
      personList.add(new Person("z4",7000.0,36));
      personList.add(new Person("z5",5000.0,22));
      personList.add(new Person("z6",4200.0,42));

      Stream<Person> personStream = personList.stream();

      personStream.map(person -> { 
   
          double old = person.getSalary();
          person.setSalary(old+1000); //增加1000
          return person; //返回原对象
      }).collect(Collectors.toList()).forEach(System.out::println);

归约(reduce)

  • 把一个流缩减成一个值
  • 作用:实现一个流的加法、乘法、求最值等计算

整个流的加法、乘法、最大值

	  List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);

      Stream<Integer> stream = list.stream();

      //整个流的加法
      Optional<Integer> add = stream.reduce((x, y) -> x + y);
      System.out.println(add.get());

      //整个流的乘法
      Optional<Integer> num = stream.reduce((x, y) -> x * y);
      System.out.println(num.get());

      //最大值
      Optional<Integer> maxNumber = stream.reduce((x, y) -> x > y ? x : y);
      System.out.println(maxNumber.get());

案例9:求所有员工的工资之和。

	  List<Person> personList = new ArrayList<Person>();
      personList.add(new Person("z1",2000.0,18));
      personList.add(new Person("z2",3200.0,15));
      personList.add(new Person("z3",1500.0,27));
      personList.add(new Person("z4",7000.0,36));
      personList.add(new Person("z5",5000.0,22));
      personList.add(new Person("z6",4200.0,42));
	  Stream<Person> personStream1 = personList.parallelStream();
      Optional<Double> sum = personStream1
              //指定选择操作薪资
              .map(person -> person.getSalary())
              .reduce((x, y) -> x + y);
      System.out.println(sum.get());

案例10:最高工资

	  List<Person> personList = new ArrayList<Person>();
      personList.add(new Person("z1",2000.0,18));
      personList.add(new Person("z2",3200.0,15));
      personList.add(new Person("z3",1500.0,27));
      personList.add(new Person("z4",7000.0,36));
      personList.add(new Person("z5",5000.0,22));
      personList.add(new Person("z6",4200.0,42));
	  Stream<Person> personStream2 = personList.parallelStream();
      Optional<Double> max = personStream2
              //指定操作salary
              .map(person -> person.getSalary())
              .reduce((x, y) -> x > y ? x : y);
      System.out.println(max.get());

收集(collect)

Stream流转List(toList)

	List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
    Stream<Integer> parallel1 = list.stream().parallel();
	List<Integer> list1 = parallel1.collect(Collectors.toList());
    list1.forEach(System.out::println);

Stream流转Set(toSet)

	List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
    Stream<Integer> parallel1 = list.stream().parallel();
	Set<Integer> set = parallel2.collect(Collectors.toSet());
    set.forEach(System.out::println);

Stream流转Map(toMap)

	List<Person> personList = new ArrayList<Person>();
    personList.add(new Person("z1", 2000.0, 18));
    personList.add(new Person("z2", 3200.0, 15));
    personList.add(new Person("z3", 1500.0, 27));
    personList.add(new Person("z4", 7000.0, 36));
    personList.add(new Person("z5", 5000.0, 22));
    personList.add(new Person("z6", 4200.0, 42));
    Stream<Person> personStream = personList.stream().parallel();
    Map<String, Person> map =
        personStream
            // toMap(k, v)
            .collect(Collectors.toMap(x -> x.getName(), y -> y));

	// lambda遍历map
    map.forEach(
        (k, v) -> { 
   
          System.out.println("key=" + k + ",v=" + v);
        });

案例11:求流的平均值

	List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 10);

    Stream<Integer> integerStream = list2.stream();

    Double averag = integerStream.collect(Collectors.averagingInt(x -> x));
    System.out.println(averag);

排序(sorted)

排序注意点

  • 排序不能用并行流,否则将失效

案例12:对纯数字进行排序

	  List<Integer> list = Arrays.asList(12, 5, 6, 3, 2, 9, 22, 17, 15, 13, 6, 5, 1);
      Stream<Integer> integerStream1 = list.stream();
      //1:对纯数字进行排序
      integerStream1.sorted(Comparator.comparingInt(x->x)).forEach(System.out::println);

案例13:将对象的薪资属性进行排序

	  List<Person> personList = new ArrayList<Person>();
      personList.add(new Person("z1",2000.0,18));
      personList.add(new Person("z2",3200.0,15));
      personList.add(new Person("z3",1500.0,27));
      personList.add(new Person("z4",7000.0,36));
      personList.add(new Person("z5",5000.0,22));
      personList.add(new Person("z6",4200.0,42));

      Stream<Person> stream = personList.stream();

      stream.sorted(Comparator.comparing(el->el.getSalary())).forEach(System.out::println);

去重和限制(distinct、limit)

	  List<Integer> list = Arrays.asList(3, 6, 6, 2, 3, 1, 2, 9, 12, 15);
      Stream<Integer> stream = list.stream();
      stream
              //去重
              .distinct()
              //分页,限制最多输出前几个
              .limit(3)
              .forEach(System.out::println);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/188997.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号