java8 —— Stream( 流 )

一、Stream( 流 )是什么?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。

集合中的 **流 **讲的是数据,此处的 Stream(流) 讲的是计算!

注意:

  • Stream 自己不会存储元素。

  • Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。

  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

二、Stream 的操作三个步骤

  • 创建Stream
    一个数据源(如:集合、数组),获取一个流
  • 中间操作
    一个中间操作链,对数据源的数据进行处理
  • 终止操作(终端操作)
    一个终止操作,执行中间操作链,并产生结果

三、创建Stream

1、Collection 提供了两个方法 stream() 与 parallelStream()

List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

2、通过 Arrays 中的 stream() 获取一个数组流

Integer[] nums = new Integer[10];
Stream<Integer> stream2 = Arrays.stream(nums);

3、 通过 Stream 类中静态方法 of()

使用Stream.of() ,通过显示值 创建一个流。它可以接收任意数量的参数。

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

4、 创建无限流

可以使用静态方法 Stream.iterate()Stream.generate() , 创建无限流。

//迭代
Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
stream4.limit(10).forEach(System.out::println);

//生成

Stream<Double> stream5 = Stream.generate(Math::random).limit(2);
stream5.forEach(System.out::println);

四、Stream 的中间操作

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

4.1、筛选与切片

  • filter : 接收 Lambda , 从流中排除某些元素。
  • limit : 截断流,使其元素不超过给定数量。
  • skip(n) : 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  • distinct : 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

示例:

public class TestStreamaAPI {	
	
	List<Employee> emps = Arrays.asList(
			new Employee(102, "李四", 59, 6666.66),
			new Employee(101, "张三", 18, 9999.99),
			new Employee(103, "王五", 28, 3333.33),
			new Employee(104, "赵六", 8, 7777.77),
			new Employee(104, "赵六", 8, 7777.77),
			new Employee(104, "赵六", 8, 7777.77),
			new Employee(105, "田七", 38, 5555.55)
	);
	
	/*
	  筛选与切片
		filter:接收 Lambda , 从流中排除某些元素。
		limit:截断流,使其元素不超过给定数量。
		skip(n) : 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
		distinct : 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
	 */
    
    //内部迭代:迭代操作 Stream API 内部完成
	@Test
	public void test2(){
		//中间操作: 不会做任何的处理
		Stream<Employee> stream = emps.stream()
			.filter((e) -> {
				System.out.println("测试中间操作");
				return e.getAge() <= 35;
			});
		
		//终止操作:一次性执行全部内容,称为“惰性求值”
		stream.forEach(System.out::println);
	}
	
	//外部迭代:自已写迭代
	@Test
	public void test3(){
		Iterator<Employee> it = emps.iterator();
		
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
	
    //只打印了两次“短路”,而不是4次。
	@Test
	public void test4(){
		emps.stream()
			.filter((e) -> {
				System.out.println("短路!"); // &&  ||
				return e.getSalary() >= 5000;
			}).limit(2)
			.forEach(System.out::println);
	}
    
	//只打印了两次“短路”,而不是4次。与test4()的区别是,取的是跳过了前面两条数据,取后面的两条数据 。
	@Test
	public void test5(){
		emps.parallelStream()
			.filter((e) -> e.getSalary() >= 5000)
			.skip(2)
			.forEach(System.out::println);
	}
    
	//必须重写Employee的 hashCode() 和 equals(),否则去重功能不生效。
	@Test
	public void test6(){
		emps.stream()
			.distinct()
			.forEach(System.out::println);
	}
}

4.2、 映射:(重点)

map :接收 Lambda , 将元素转换成其他形式或提取信息。 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

flatMap : 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

@Test
public void test1(){
    Stream<String> str = emps.stream()
        .map((e) -> e.getName());

    System.out.println("-------------------------------------------");

    List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

    strList.stream()
        .map(String::toUpperCase)		
        .forEach(System.out::println);

    System.out.println("=====================================");

    //将Employee 中的姓名提取出来
    emps.stream()
        .map(Employee::getName)
        .forEach(System.out::println);

    System.out.println("=====================================");


    //filterCharacter()方法是每个字符返回一个流,
    Stream<Stream<Character>> stream2 = strList.stream()
        .map(TestStreamAPI1::filterCharacter);//  {{a,a,a},{b,b,b},{c,c,c}}

    stream2.forEach((sm) -> {
        sm.forEach(System.out::println); //{a,a,a,b,b,b,c,c,c}
    });

    System.out.println("=====================================");


    //
    Stream<Character> stream3 = strList.stream()
        .flatMap(TestStreamAPI1::filterCharacter);

    stream3.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str){
    List<Character> list = new ArrayList<>();

    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }
    return list.stream();
}

4.3、 排序:

  • sorted() :自然排序 ( Comparable )
  • sorted(Comparator com) : 定制排序
@Test
public void test2(){
    //自然排序,按照String 内置的Comparable 排序
    emps.stream()
        .map(Employee::getName)
        .sorted()
        .forEach(System.out::println);

    System.out.println("------------------------------------");

    //定制排序
    emps.stream()
        .sorted((x, y) -> {
            if(x.getAge() == y.getAge()){
                return x.getName().compareTo(y.getName());
            }else{
                return Integer.compare(x.getAge(), y.getAge());
            }
        }).forEach(System.out::println);
}

五、Stream 的终止操作

5.1、查找与匹配

allMatch :检查是否匹配所有元素
anyMatch :检查是否至少匹配一个元素
noneMatch :检查是否没有匹配的元素
findFirst :返回第一个元素
findAny :返回当前流中的任意元素
count :返回流中元素的总个数
max :返回流中最大值
min :返回流中最小值

forEach:内部迭代

5.2、 归约:(重点)

将流中元素反复结合起来,得到一个值。

reduce(T identity, BinaryOperator) 返回结果是T
reduce(BinaryOperator) 返回结果是Optional<T>

	@Test
	public void test1(){
		List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
		
        //起始值是0,肯定不为空,所以返回值是Integer
		Integer sum = list.stream()
			.reduce(0, (x, y) -> x + y);
		
		System.out.println(sum);
		
		System.out.println("----------------------------------------");
		
        //因为没有起始值,所以返回值是 Optional
		Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.reduce(Double::sum);
		
		System.out.println(op.get());
	}

5.3、收集:(重点)

将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法。

collect(Collector c)

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

	List<Employee> emps = Arrays.asList(
			new Employee(102, "李四", 79, 6666.66, Status.BUSY),
			new Employee(101, "张三", 18, 9999.99, Status.FREE),
			new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
			new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(105, "田七", 38, 5555.55, Status.BUSY)
	);

	@Test
	public void test4(){
		
		// 最大值
		Optional<Double> max = emps.stream()
			.map(Employee::getSalary)
			.collect(Collectors.maxBy(Double::compare));
		
		System.out.println(max.get());
		
		//最少的工资
		Optional<Employee> op = emps.stream()
			.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
		
		System.out.println(op.get());
		
		//工资的总和
		Double sum = emps.stream()
			.collect(Collectors.summingDouble(Employee::getSalary));
		
		System.out.println(sum);
		
		//工资的平均值
		Double avg = emps.stream()
			.collect(Collectors.averagingDouble(Employee::getSalary));
		
		System.out.println(avg);
		
		// 总数
		Long count = emps.stream()
			.collect(Collectors.counting());
		System.out.println(count);
		System.out.println("--------------------------------------------");
		
		
		DoubleSummaryStatistics dss = emps.stream()
			.collect(Collectors.summarizingDouble(Employee::getSalary));
		
		System.out.println(dss.getMax());
	}

5.4、分组

Collectors.groupingBy();

	//分组
	@Test
	public void test5(){
		Map<Status, List<Employee>> map = emps.stream()
			.collect(Collectors.groupingBy(Employee::getStatus));
		
		System.out.println(map);
	}

运行结果:

{VOCATION=[Employee [id=103, name=王五, age=28, salary=3333.33, status=VOCATION]], BUSY=[Employee [id=102, name=李四, age=79, salary=6666.66, status=BUSY], Employee [id=104, name=赵六, age=8, salary=7777.77, status=BUSY], Employee [id=105, name=田七, age=38, salary=5555.55, status=BUSY]], FREE=[Employee [id=101, name=张三, age=18, salary=9999.99, status=FREE], Employee [id=104, name=赵六, age=8, salary=7777.77, status=FREE], Employee [id=104, name=赵六, age=8, salary=7777.77, status=FREE]]}

多级分组:

	//多级分组
	@Test
	public void test6(){
		Map<Status, Map<String, List<Employee>>> map = emps.stream()
			.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
				if(e.getAge() >= 60)
					return "老年";
				else if(e.getAge() >= 35)
					return "中年";
				else
					return "成年";
			})));
		
		System.out.println(map);
	}

运行结果:

{VOCATION={成年=[Employee [id=103, name=王五, age=28, salary=3333.33, status=VOCATION]]}, FREE={成年=[Employee [id=101, name=张三, age=18, salary=9999.99, status=FREE], Employee [id=104, name=赵六, age=8, salary=7777.77, status=FREE], Employee [id=104, name=赵六, age=8, salary=7777.77, status=FREE]]}, BUSY={成年=[Employee [id=104, name=赵六, age=8, salary=7777.77, status=BUSY]], 老年=[Employee [id=102, name=李四, age=79, salary=6666.66, status=BUSY]], 中年=[Employee [id=105, name=田七, age=38, salary=5555.55, status=BUSY]]}}

5.5、分区

Collectors.partitioningBy()

	@Test
	public void test7(){
		Map<Boolean, List<Employee>> map = emps.stream()
			.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
		
		System.out.println(map);
	}

5.6、前缀,后缀

Collectors.joining()

	@Test
	public void test8(){
		String str = emps.stream()
			.map(Employee::getName)
			.collect(Collectors.joining("," , "----", "----"));
		
		System.out.println(str);
	}

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/89315504