【Java8】Stream-中间操作

2.中间操作

(一)筛选与切片

(1)filter-过滤,接收Lambda,从流中排除某些元素
//内部迭代:迭代操作有Stream API完成
@Test
public void test1(){
	//多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理
	//而在终止操作时一次性全部处理,称为“惰性求值”
	
	//中间操作:不会执行任何操作
	Stream<Employee> stream=employees.stream()
					  .filter((e)->{
						  System.out.println("Stream API 的中间操作");
						  return e.getAge()>35;
					  });
	//终止操作:一次性执行全部内容
	stream.forEach(System.out::println);
}

//外部迭代:
@Test
public void test2(){
	Iterator<Employee> it=employees.iterator();
	
	while(it.hasNext()){
		System.out.println(it.next());
	}
}
(2)limit-截断流,使其元素不超过给定数量
@Test
public void test3(){
	employees.stream()
			 .filter((e)->{
				 System.out.println("----");
				 return e.getSalary()>5000;
			 })
			 .limit(2)
			 .forEach(System.out::println);
	
}
(3)skip(n)-跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流,与limit(n)互补
@Test
public void test4(){
	employees.stream()
		     .filter((e)->e.getSalary()>5000)
		     .skip(2)
		     .forEach(System.out::println);
}
(4)distinct-筛选,通过流所生成元素的hashCode()和equals()去除重复元素
@Test
public void test5(){
	employees.stream()
     .filter((e)->e.getSalary()>5000)
     .skip(2)
     .distinct()
     .forEach(System.out::println);		
}

(二)映射

(1)map——接收lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
public void test6(){
	List<String> list=Arrays.asList("1","2","3","4","5");
	
	list.stream()
		.map((str)->str.toUpperCase())
		.forEach(System.out::println);
	
	System.out.println("-------------------------");
	
	employees.stream()
			 .map(Employee::getName)
			 .forEach(System.out::println);
	
	System.out.println("-------------------------");
}
(2)flatMap-接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流。
public void test7(){
	employees.stream()
			 .map(Employee::getName)
			 .forEach(System.out::println);
	
	System.out.println("-------------------------");
	
	Stream<Character> sm = list.stream()
							   .flatMap(TestStreamAPI2::filterCharacter);
							   
    sm.forEach(System.out::println);
}

(三)排序

(1)sorted()-自然排序(Comparable)
@Test
public void test8(){
	List<String> list=Arrays.asList("4","1","3","5","2");
	
	list.stream()
		.sorted()
		.forEach(System.out::println);
	
	System.out.println("-------------------------");
}
(2)sorted(Comparator com)-定制排序(Comparator)
@Test
public void test9(){
	List<String> list=Arrays.asList("4","1","3","5","2");
	
	employees.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);
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值