Stream流简介
Stream的操作步骤
1、创建Stream流
2、中间流水线操作
3、终止操作,产生需要的结果源数据
注意:Stream流和最终产生的结果不影响
创建Stream的代码示例
List<String> list = Arrays.asList("Sarah", "Terry", "Selina", "Tom");
// 创建Stream
@Test
public void test01(){
// 1、通过Collection提供的stream()或者 paralleStream()
Stream<String> stream01 = list.stream();
// 2、通过Stream类的静态方法of()
Stream<String> stream02 = Stream.of("aa", "bb", "cc");
// 3、通过Arrays的静态方法 stream() 获取数组流
Stream<Integer> stream03 = Arrays.stream(new Integer[]{1,1,1});
// 4、创建无限流
Stream<Integer> stream04 = Stream.iterate(0,(x) -> x+2);
stream04.limit(10).forEach(System.out::println);
}
Stream的中间操作:筛选与切片
代码示例:
List<String> strList = Arrays.asList("Sarah", "Terry", "Selina", "Tom", "Selina", "Terry");
List<Employee> employeeList = Arrays.asList(
new Employee("张三",18,2000),
new Employee("李四",58,3000),
new Employee("王五",48,7000),
new Employee("陈六",38,9000),
new Employee("田七",18,9000),
new Employee("田七",18,9000),
new Employee("田七",18,9000)
);
//中间操作
/**
* 筛选与切片
* filter:从流中排除某些元素
* limit(n):从流中取不超过给n的元素
* skip(n):返回一个去掉前n个元素的流,若流中元素不超过n,返回一个空流,与limit互补
* distinct:根据hashCode()和equals()对元素去重
*/
// filter
@Test
public void test01(){
// 中间操作
Stream<String> stream = strList.stream().filter((x) -> x.length() > 3);
// 终止操作
stream.forEach(System.out::println);
}
// limit
@Test
public void test02(){
employeeList.stream().limit(2).forEach(System.out::println);
}
// skip
@Test
public void test03(){
employeeList.stream().skip(2).forEach(System.out::println);
}
// distinct
@Test
public void test04(){
strList.stream().distinct().forEach(System.out::println);
}
// 惰性求值
@Test
public void test05(){
employeeList.stream()
.filter((x) -> {
System.out.println("短路");
return x.getAge() >50;
})
.limit(2)
.forEach(System.out::println);
}
惰性求值