Java8的Stream API使用

案例一:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 * @author xyphf
 * @date 2018年8月23日
 * 
 * 一、Stream 的三个操作步骤
 * 
 * 1、创建Stream
 * 
 * 2、中间操作
 * 
 * 3、终止操作(终端操作)
 */
public class TestStreamAPI1 {
	
	// 创建 Stream
	@Test
	public void test1() {
		//1. 可以通过Collection 系列集合提供的 stream() 获取串行流  或 parallelStream()获取并行流
		List<String> list = new ArrayList<>();
		// 第一种获取流的方式
		Stream<String> stream1 = list.stream();
		
		//2. 通过Arrays 种的静态方法stream() 获取数组流
		// 第二种获取流的方式
		Employee[] emps = new Employee[10];
		Stream<Employee> stream2 = Arrays.stream(emps);
		
		//3. 通过Stream类中的静态方法 of()方法
		// 第三中获取流的方式
		Stream<String> stream3 = Stream.of("aa","bb","cc");
		
		//4. 创建无限流
		
		// 迭代
		// 第四种创建流的方式
		Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
//		stream4.forEach(System.out::println);
		// 加一部中间操作,限制数量
		stream4.limit(10).forEach(System.out::println);
		
		// 生成
		Stream.generate(() -> Math.random())
		.limit(5)
		.forEach(System.out::println);
	}
}

案例二:

Stream的中间操作

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 * 一、Stream 的三个操作步骤
 * 
 * 1、创建Stream
 * 
 * 2、中间操作
 * 
 * 3、终止操作(终端操作)
 */
public class TestStreamAPI2 {
	
	List<Employee> emps = Arrays.asList(
			new Employee(101, "张三", 18, 9999.99),
			new Employee(102, "李四", 59, 5555.55),
			new Employee(103, "王五", 26, 3333.33),
			new Employee(104, "赵六", 36, 6666.66),
			new Employee(105, "田七", 12, 8888.88),
			new Employee(105, "田七", 12, 8888.88),
			new Employee(105, "田七", 12, 8888.88)
	);

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

	// 内部迭代: 迭代操作由Stream API完成
	@Test
	public void test1() {
		// 中间操作:不会执行任何操作
//		Stream<Employee> stream = emps.stream()
//							.filter((e) -> e.getAge() > 35);
//		stream.forEach(System.out::println);
		
		Stream<Employee> stream = emps.stream()
								  .filter((e) -> {
									System.out.println("Stream API 的中间操作");
									return e.getAge() > 35;
								  });
		// 终止操作:一次性执行全部内容,即“惰性求值”
		stream.forEach(System.out::println);
	}
	
	// 外部迭代:我们自己写的迭代
	@Test
	public void test2() {
		Iterator<Employee> it = emps.iterator();
		
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
	
	@Test
	public void test3() {
//		emps.stream()
//				.filter((e) -> e.getSalary() > 5000)
//				.limit(2)
//				.forEach(System.out::println);
		emps.stream()
		.filter((e) -> {
			System.out.println("短路!");
			return e.getSalary() > 5000;
		})
		.limit(2)
		.forEach(System.out::println);
	}
	
	@Test
	public void test4(){
//		emps.stream()
//		.filter((e)->e.getSalary() > 5000)
//		.skip(2)
//		.forEach(System.out::println);
		emps.stream()
			.filter((e)->e.getSalary() > 5000)
			.skip(2)
			.distinct() // 要想去重成功,emps实体类里 必须重写hashCode() 和 equals()
			.forEach(System.out::println);
	}

	//中间操作
	/*
	 * 映射
	 * map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
	 * flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
	 */
	
	@Test
	public void test5(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		list.stream()
			.map((str) -> str.toUpperCase())
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
		emps.stream()
			.map(Employee::getName)
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
//		Stream<Stream<Character>> stream = list.stream()
//			.map(TestStreamAPI2::filterCharacter);
//		
//		stream.forEach((sm) ->{
//			sm.forEach(System.out::println);
//		});
		
		System.out.println("-------------------------------");
		
		Stream<Character> sm = list.stream()
				.flatMap(TestStreamAPI2::filterCharacter);
		
		sm.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();
	}
	
	public void test6(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		List list2 = new ArrayList();
		list2.add(11);
		list2.add(22);
		list2.addAll(list);
	}
	
	//中间操作
	/**
	 * 排序
	 * sorted()--自然排序(Comparable)
	 * sorted(Comparator com)--定制排序(Comparator)
	 */
	
	public void test7(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		list.stream()
			.sorted()
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
		emps.stream()
			.sorted((e1, e2) -> {
				if(e1.getAge().equals(e2.getAge())){
					return e1.getName().compareTo(e2.getName());
				} else {
					return -e1.getAge().compareTo(e2.getAge());
				}
			}).forEach(System.out::println);
	}
	
}

案例三:

 

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.junit.Test;

import com.atguigu.java8.Employee.Status;

/*
 * 终止操作 
 */
public class TestStreamAPI3 {
	
	List<Employee> employes = 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(105, "田七", 38, 5555.55, Status.BUSY)
	);
	
	/*
	 * 查找与匹配
	 * allMatch——检查是否匹配所有元素
	 * anyMatch——检查是否至少匹配一个元素
	 * noneMatch——检查是否没有匹配所有元素
	 * findFirst——返回第一个元素
	 * findAny——返回当前流中的任意元素
	 * count——返回流中元素的个数
	 * max——返回流中最大值
	 * min——返回流中最小值
	 */
	@Test
	public void test1(){
			// allMatch——检查是否匹配所有元素
		 boolean b1 = employes.stream()
					.allMatch((e) -> e.getStatus().equals(Status.BUSY));
			System.out.println(b1);
			
			// anyMatch——检查是否至少匹配一个元素
		 boolean b2 = employes.stream()
					.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
		 	System.out.println(b2);
		 	
		 	// noneMatch——检查是否没有匹配所有元素
		 boolean b3 = employes.stream()
		 			.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
		 	System.out.println(b3);
		 	
		 // 按工资正排序 并查询第一个 工资最低的
		  Optional<Employee> op = employes.stream()
		 			.sorted((e1,e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
		 			.findFirst();
		  // 如果op里面的值是空的,那么你就有一个替代的对象
		  // op.orElse(other);
		  System.out.println(op.get());
		  
			 // 按工资倒排序 并查询第一个 工资最高的 在前面加一个-号
		  Optional<Employee> op1 = employes.stream()
		 			.sorted((e1,e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
		 			.findFirst();
		  // 如果op里面的值是空的,那么你就有一个替代的对象
		  // op.orElse(other);
		  System.out.println(op1.get());
		  
		  // findAny——返回当前流中的任意元素
		  Optional<Employee> op2 = employes.parallelStream()
		  		  .filter((e) -> e.getStatus().equals(Status.FREE))
		  		  .findAny();
		  System.out.println(op2.get());  
	}
	
	@Test
	public void test2(){
		// count——返回流中元素的个数
		Long count = employes.stream()
				.count();
		System.out.println(count); 
		
		// max——返回流中最大值
		Optional<Employee> op1 = employes.stream()
				.max((e1,e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
		System.out.println(op1); 
		
		// 获取最少工资是多少
		Optional<Double> op2 = employes.stream()
				.map(Employee::getSalary)
				.min(Double::compare);
		System.out.println(op2.get()); 
	}
	
	/*
	 * 规约
	 * reduce(T identity,BinaryOperator) / reduce(BinaryOperator) —— 可以将流中元素反复结合起来,得到一个值。
	 */
	@Test
	public void test3(){
		List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
		Integer sum = list.stream()
			.reduce(0, (x,y) -> x + y);
		System.out.println(sum); 
		
		System.out.println("-------------------------------");
		
		// 计算当前公司的工资总和是多少
		Optional<Double> op = employes.stream()
				.map(Employee::getSalary)
				.reduce(Double::sum);
		System.out.println(op.get());
	}
	
	/*
	 * collect——将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
	 */
	@Test
	public void test4(){
		// 将所有的员工名字放入list
		List<String> list = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.toList());
		list.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		// 将所有的员工名字放入Set 去重
		Set<String> set = employes.stream()
						.map(Employee::getName)
						.collect(Collectors.toSet());
		set.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		HashSet<String> hs = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.toCollection(HashSet::new));
		hs.forEach(System.out::println);
	}
	
	@Test
	public void test5(){
		// 总数
		Long count = employes.stream()
				.collect(Collectors.counting());
		System.out.println(count);
		
		System.out.println("-------------------------------");
		// 平均值
		Double avg = employes.stream()
				.collect(Collectors.averagingDouble(Employee::getSalary));
		System.out.println(avg);
		
		//总和
		Double sum = employes.stream()
				.collect(Collectors.summingDouble(Employee::getSalary));	
		System.out.println(sum);
		
		System.out.println("-------------------------------");
		// 求最大值
		Optional<Double> max = employes.stream()
				.map(Employee::getSalary)
				.collect(Collectors.maxBy(Double::compare));
		System.out.println(max.get());
		
		System.out.println("-------------------------------");
		// 最小值
		Optional<Employee> op = employes.stream()
				.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
		System.out.println(op.get());
	}
	
	// 分组
	@Test
	public void test6(){
		Map<Status, List<Employee>> map = employes.stream()
				.collect(Collectors.groupingBy(Employee::getStatus));
		System.out.println(map);
	}
	
	// 多级分组
	@Test
	public void test7(){
		Map<Status, Map<String, List<Employee>>> map = employes.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);
	}
	
	// 分区  满足条件的一个区,不满足条件的一个区
	@Test
	public void test8(){
		Map<Boolean, List<Employee>> map = employes.stream()
				.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
		System.out.println(map);
	}
	
	// 组函数的另一种获取方式
	@Test
	public void test9(){
		DoubleSummaryStatistics dss = employes.stream()
				.collect(Collectors.summarizingDouble(Employee::getSalary));
		System.out.println(dss.getSum());
		System.out.println(dss.getAverage());
		System.out.println(dss.getMax());
	}
	
	// 连接字符串
	@Test
	public void test10(){
		String str = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.joining("," , "----", "----"));	
		System.out.println(str);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值