谈谈Stream流式处理

感谢尚硅谷康师傅!!!康师傅yyds
Streaf API说明

Java8中有两大最为重要的改变。第一个是LanIbda表达式;另外一个则是Stream API。

Stream APl ( java.util.stream)把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简言之,Stream API提供了一种高效且易于使用的处理数据的方式。

在这里插入图片描述

在这里插入图片描述

Stream是一个延迟操作,一旦执行终止操作,才执行中间操作

在这里插入图片描述

1.Stream关注的是对数据的运算,与CPU打交道集合关注的是数据的存储,与内存打交道

2.Stream 自己不会存储元素。Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream .Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行

3.stream执行沉程
Stream的实例化
—系列的中间操作(过滤、映射、…)终止操作

4.说明:
4.1一个中间操作链·对数据源的数据进行处理
4.2一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

在这里插入图片描述

创建Stream

在这里插入图片描述

default Stream<E> stream():返回一个顺序流
default Stream<E> parallelStream():返回一个并行流
        //创建Stream方式一:通过集合
        List<Employee> employees = EmployeeData.getEmployees();
        //  default Stream<E> stream() :返回一个顺序流
        Stream<Employee> stream = employees.stream();

        //  default Stream<E> paralleLStream():返回一个并行流
        Stream<Employee> parallelStream = employees.parallelStream();

在这里插入图片描述

        //创建Stream 方式二:通过数组
        int [] arr= new int[]{1,2,3,4,5,6};
        调用Arrays类的static <T> stream<T> stream(T[ ] array):返回一个流
        //调用Arrays.stream
        IntStream stream1 = Arrays.stream(arr);
        

也可用泛型创建

在这里插入图片描述

在这里插入图片描述

       //3.创建Stream 方式三:通过Stream 类中的静态方法of()
		Stream<String> stream3=Stream.of("aa","bb","cc");

在这里插入图片描述

       //4.创建无限流
		//迭代
		Stream<Integer> stream4=Stream.iterate(0, t -> t+2);
		stream4.limit(10).forEach(System.out::println);
      

       //生成
		Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println);
中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性处理,成为“惰性求值”。

1.筛选与切片

在这里插入图片描述

//中间操作
	
	List<Employee> employees=Arrays.asList(
			new Employee("张三",18,9999.99),
			new Employee("李四",58,5555.55),
			new Employee("王五",26,3333.33),
			new Employee("赵六",36,6666.66),
			new Employee("田七",12,8888.88),
			new Employee("田七",12,8888.88)
			);

/* 筛选与切片

  • filter–接收Lambda,从流中排除某些元素。
  • limit–截断流,使其元素不超过给定数量。
  • skip(n)–跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补
  • distinct–筛选,通过流所生成元素的 hashCode() 和 equals()掉重复元素
    */
//内部迭代:迭代操作由 Stream API 完成
	@Test
	public void test1(){
		//中间操作:不会执行任何操作
		Stream<Employee> stream=employees.stream()
								.filter((e) -> e.getAge()>35 );
		//终止操作:一次性执行全部内容,即 惰性求值
		stream.forEach(System.out::println);
	}

//Limit(n)——截断流,使其元素不超过给定数量。
list.stream().limit(3).foreach(System.out::println);


employees.stream()
				 .filter((e)->e.getSalary()>5000)
				 .skip(2)//跳过前两个
				 .distinct()//去重,注意:需要Employee重写hashCode 和 equals 方法
				 .forEach(System.out::println);

2.映射

在这里插入图片描述

//中间操作
	/*
	 * 映射
	 * map--接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新元素。
	 * flatMap--接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
	 */
List<String> list=Arrays.asList("aaa","bbb","ccc","ddd");
		list.stream()
			 .map((str)->str.toUpperCase())
			 .forEach(System.out::println);
		
		System.out.println("------------------------");
		
		employees.stream()
			     .map(Employee::getName)
			     .forEach(System.out::println);


flatMap没懂

3.排序

在这里插入图片描述

List<Integer> list = Arrays.aslist(12436534870-987);
list.stream().sorted().forEach(System.out::print1n);

 List<String> list=Arrays.asList("ccc","bbb","aaa");
        list.stream()
                .sorted()
                .forEach(System.out::println);

employees.stream( ).sorted((e1,e2) -> {
return Integer.compare(e1.getAge() ,e2.getAge()).forEach(System.out : : println);



在这里插入图片描述

终止操作

终止操作会从流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是void。

1.查找与匹配

在这里插入图片描述

	List<Employee> employees=Arrays.asList(
			new Employee("张三",18,9999.99,Status.FREE),
			new Employee("李四",58,5555.55,Status.BUSY),
			new Employee("王五",26,3333.33,Status.VOCATION),
			new Employee("赵六",36,6666.66,Status.FREE),
			new Employee("田七",12,8888.88,Status.BUSY)
			);
	/*
	 * 查找与匹配
	 * 
	 */
	
	@Test
	public void test1(){
		boolean b1=employees.stream()//allMatch-检查是否匹配所有元素
							.allMatch((e)->e.getStatus().equals(Status.BUSY));
		System.out.println(b1);//false
		
		boolean b2=employees.stream()//anyMatch-检查是否至少匹配一个元素
							.anyMatch((e)->e.getStatus().equals(Status.BUSY));
		System.out.println(b2);//true
		
		boolean b3=employees.stream()//noneMatch-检查是否没有匹配所有元素
		         			.noneMatch((e)->e.getStatus().equals(Status.BUSY));
		System.out.println(b3);//false
		
		Optional<Employee> op=employees.stream()//findFirst-返回第一个元素//Optional是Java8中避免空指针异常的容器类
				 .sorted((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary()))
				 .findFirst();
		System.out.println(op.get());//Employee [name=王五, age=26, salary=3333.33, Status=VOCATION]
		
		Optional<Employee> op2=employees.parallelStream()//findAny-返回当前流中的任意元素
										.filter((e)->e.getStatus().equals(Status.FREE))
										.findAny();
		System.out.println(op2.get());//Employee [name=赵六, age=36, salary=6666.66, Status=FREE]
		
		Long count=employees.stream()//count-返回流中元素的总个数
				            .count();
		System.out.println(count);//5
		
		Optional<Employee> op3=employees.stream()//max-返回流中最大值
				                        .max((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary()));
		System.out.println(op3.get());//Employee [name=张三, age=18, salary=9999.99, Status=FREE]
		
		Optional<Double> op4=employees.stream()//min-返回流中最小值
				                      .map(Employee::getSalary)
				                      .min(Double::compare);
		System.out.println(op4.get());//3333.33
	}

2.归约

在这里插入图片描述

备注:map和reduce的连接通常称为map-reduce 模式,因google用它来进行网络搜索而出名。

	/*
	 * 归约
	 * reduce(T identity,BinaryOperator b) / reduce(BinaryOperator b)-可以将流中元素反复结合起来,得到一个值。
	 */
	@Test
	public void test3(){
		List<Integer> list=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
		Integer sum=list.stream()//reduce(T identity,BinaryOperator b)
				        .reduce(0, (x,y)->x+y);//0为起始值
		System.out.println(sum);
		
		System.out.println("--------------------------");
		
		Optional<Double> op=employees.stream()//reduce(BinaryOperator b)//没有起始值,map返回可能为空,所以返回Optional类型
				                     .map(Employee::getSalary)
				                     .reduce(Double::sum);
		System.out.println(op.get());
	}

3.收集

在这里插入图片描述

Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

在这里插入图片描述

在这里插入图片描述

	/*
	 * 收集
	 * collect-将流转换为其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
	 */
	@Test
	public void test4(){
		List<String> list=employees.stream()
				                   .map(Employee::getName)
				                   .collect(Collectors.toList());
		list.forEach(System.out::println);
		
		System.out.println("----------------------------");
		
		Set<String> set=employees.stream()
				                 .map(Employee::getName)
				                 .collect(Collectors.toSet());
		set.forEach(System.out::println);
		
		System.out.println("----------------------------");
		
		HashSet<String> hs=employees.stream()
				                    .map(Employee::getName)
				                    .collect(Collectors.toCollection(HashSet::new));
		hs.forEach(System.out::println);
		
		System.out.println("----------------------------");
		
		//总和
		Long count=employees.stream()
				            .collect(Collectors.counting());
		System.out.println(count);
		
		//平均值
		Double avg=employees.stream()
				            .collect(Collectors.averagingDouble(Employee::getSalary));
		System.out.println(avg);
		
		//总和
		Double sum=employees.stream()
				            .collect(Collectors.summingDouble(Employee::getSalary));
		System.out.println(sum);
		
		//最大值
		Optional<Employee> max=employees.stream()
				                        .collect(Collectors.maxBy((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary())));
		System.out.println(max.get());
		
		//最小值
		Optional<Double> min=employees.stream()
				                      .map(Employee::getSalary)
				                      .collect(Collectors.minBy(Double::compare));
		System.out.println(min.get());
		
		System.out.println("----------------------------");
		
		//分组
		Map<Status,List<Employee>> map=employees.stream()
				                                .collect(Collectors.groupingBy(Employee::getStatus));
		System.out.println(map);//{FREE=[Employee [name=张三, age=18, salary=9999.99, Status=FREE], Employee [name=赵六, age=36, salary=6666.66, Status=FREE]], VOCATION=[Employee [name=王五, age=26, salary=3333.33, Status=VOCATION]], BUSY=[Employee [name=李四, age=58, salary=5555.55, Status=BUSY], Employee [name=田七, age=12, salary=8888.88, Status=BUSY]]}
		
		//多级分组
		Map<Status,Map<String,List<Employee>>> map2=employees.stream()
				                                            .collect( Collectors.groupingBy( Employee::getStatus,Collectors.groupingBy((e)->{
				                                            	if(e.getAge()<=35){
				                                            		return "青年";
				                                            	}else if(e.getAge()<=50){
				                                            		return "中年";
				                                            	}else{
				                                            		return "老年";
				                                            	}
				                                            }) ) );
		System.out.println(map2);//{FREE={青年=[Employee [name=张三, age=18, salary=9999.99, Status=FREE]], 中年=[Employee [name=赵六, age=36, salary=6666.66, Status=FREE]]}, VOCATION={青年=[Employee [name=王五, age=26, salary=3333.33, Status=VOCATION]]}, BUSY={青年=[Employee [name=田七, age=12, salary=8888.88, Status=BUSY]], 老年=[Employee [name=李四, age=58, salary=5555.55, Status=BUSY]]}}
		
		//分区
		Map<Boolean,List<Employee>> map3=employees.stream()
				                                 .collect(Collectors.partitioningBy((e)->e.getSalary()>8000));
		System.out.println(map3);//{false=[Employee [name=李四, age=58, salary=5555.55, Status=BUSY], Employee [name=王五, age=26, salary=3333.33, Status=VOCATION], Employee [name=赵六, age=36, salary=6666.66, Status=FREE]], true=[Employee [name=张三, age=18, salary=9999.99, Status=FREE], Employee [name=田七, age=12, salary=8888.88, Status=BUSY]]}
		
		System.out.println("--------------------------------");
		
		DoubleSummaryStatistics dss=employees.stream()
				                             .collect(Collectors.summarizingDouble(Employee::getSalary));
		System.out.println(dss.getSum());
		System.out.println(dss.getAverage());
		System.out.println(dss.getMax());
		
		System.out.println("--------------------------------");
		String strr=employees.stream()
				             .map(Employee::getName)
				             .collect(Collectors.joining(","));
		System.out.println(strr);//张三李四王五赵六田七
	 }

rs.summarizingDouble(Employee::getSalary));
System.out.println(dss.getSum());
System.out.println(dss.getAverage());
System.out.println(dss.getMax());

	System.out.println("--------------------------------");
	String strr=employees.stream()
			             .map(Employee::getName)
			             .collect(Collectors.joining(","));
	System.out.println(strr);//张三李四王五赵六田七
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值