筛选与切面
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());
}
}
映射
- map——接收lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素(接收一个返回一个)。
public void test6(){
List<String> list=Arrays.asList("aa",bb","cc","dd","ee");
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("-------------------------");
}
排序
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("-------------------------");
}
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);
}