编程语言
首页 > 编程语言> > JAVA8新api(二)

JAVA8新api(二)

作者:互联网

STREAM:

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。 “集合讲的是数据,流讲的是计算!”

注意:
①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。

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

创建流:

//1. Collection 提供了两个方法  stream() 与 parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

//2. 通过 Arrays 中的 stream() 获取一个数组流
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
		
//3. 通过 Stream 类中静态方法 of()
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
		
//4. 创建无限流
//迭代
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
		
//生成
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
		

 

中间操作:

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

filter——接收 Lambda , 从流中排除某些元素。
limit——截断流,使其元素不超过给定数量。
skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
//所有的中间操作不会做任何的处理
Stream<Employee> stream = emps.stream()
			.filter((e) -> {
				System.out.println("测试中间操作");
				return e.getAge() <= 35;
			});	

		emps.stream()
			.filter((e) -> {
				System.out.println("短路!"); // &&  ||
				return e.getSalary() >= 5000;
			}).limit(3)
		
	
		emps.parallelStream()
			.filter((e) -> e.getSalary() >= 5000)
			.skip(2)
		
	
	
		emps.stream()
			.distinct()
			.forEach(System.out::println);
	

  

映射
map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

Stream<String> str = emps.stream()
			.map((e) -> e.getName());
		
		
List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
Stream<String> stream = strList.stream()
			   .map(String::toUpperCase);
		
		
Stream<Stream<Character>> stream2 = strList.stream()
			   .map(TestStreamAPI1::filterCharacter);
		
==========================================

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

public static Stream<Character> filterCharacter(String str){
		List<Character> list = new ArrayList<>();
		
		for (Character ch : str.toCharArray()) {
			list.add(ch);
		}
		
		return list.stream();
	}

  

终止操作:

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

allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
noneMatch——检查是否没有匹配的元素
findFirst——返回第一个元素
findAny——返回当前流中的任意元素
count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值
boolean bl = emps.stream()
			.allMatch((e) -> e.getStatus().equals(Status.BUSY));
			
			
boolean bl1 = emps.stream()
			.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
						
			
boolean bl2 = emps.stream()
			.noneMatch((e) -> e.getStatus().equals(Status.BUSY));

Optional<Employee> op = emps.stream()
			.sorted((e1, e2) -> Double.compare(e1.getSalary(), 
                       e2.getSalary()))
			.findFirst();


Optional<Employee> op2 = emps.parallelStream()
			.filter((e) -> e.getStatus().equals(Status.FREE))
			.findAny();


long count = emps.stream()
			.filter((e) -> e.getStatus().equals(Status.FREE))
			 .count();

Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.max(Double::compare);


Optional<Employee> op2 = emps.stream()
			.min((e1, e2) -> Double.compare(e1.getSalary(), 
                        e2.getSalary()));

  

归约
reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
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);
	
		
Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.reduce(Double::sum);


//搜索名字中 “六” 出现的次数
Optional<Integer> sum = emps.stream()
			.map(Employee::getName)
			.flatMap(TestStreamAPI1::filterCharacter)
			.map((ch) -> {
				if(ch.equals('六'))
					return 1;
				else 
					return 0;
			}).reduce(Integer::sum);

  

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

//把流中元素收集到List
List<String> list = emps.stream() .map(Employee::getName) .collect(Collectors.toList()); //把流中元素收集到Set  Set<String> set = emps.stream() .map(Employee::getName) .collect(Collectors.toSet()); HashSet<String> hs = emps.stream() .map(Employee::getName) .collect(Collectors.toCollection(HashSet::new)); Optional<Double> max = emps.stream() .map(Employee::getSalary) .collect(Collectors.maxBy(Double::compare)); Optional<Employee> op = emps.stream() .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); Double sum = emps.stream() .collect(Collectors.summingDouble(Employee::getSalary)); Double avg = emps.stream() .collect(Collectors.averagingDouble(Employee::getSalary)); Long count = emps.stream() .collect(Collectors.counting()); //收集流中Double属性的统计值
DoubleSummaryStatistics dss = emps.stream() .collect(Collectors.summarizingDouble(Employee::getSalary));

  

标签:map,元素,stream,Stream,getSalary,api,emps,JAVA8
来源: https://www.cnblogs.com/holycai/p/15261638.html