Stream
介绍
- 用于对集合数据进行操作(执行非常复杂的查找、过滤和映射数据等)
- 用于操作数据源(集合、数组等)所生成的元素序列
-
注意:
①Stream 不会存储元素。
②Stream 不会改变源对象,会返回一个持有结果的新Stream。
③Stream 操作是延迟执行,需要结果的时候才执行
使用
创建
-
Collection 接口:
default Stream<E> stream() : 返回一个顺序流
efault Stream<E> parallelStream():返回一个并行流
-
数组(Arrays)
static <T> Stream<T> stream(T[] array)
public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)
-
Stream方法
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
- 迭代型public static<T> Stream<T> generate(Supplier<T> s
- supplier产生
中间操作
对数据源的数据进行处理
删选切片
映射
//map
Stream<String> str = emps.stream()
.map((e) -> e.getName())
Stream<String> stream = strList.stream()
.map(String::toUpperCase);
//flatmap - 类似多个list合并为一个list
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();
}
排序
regionList.stream().sorted(Comparator.comparing(RegionDTO::getCode)).collect(Collectors.toList());
终止
执行中间操作链,并产生结果(结果可以是任何不是流的值)
查找匹配
归约
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);
收集