概述:
“Stream流”其实是一个集合元素的函数模型,它并不是集合,也不是数据结构,其本身并不存储任何元素(或其地址值)。
获取流:
1. 所有的Collection集合都可以通过stream默认方法获取流
2. Stream接口的静态方法of可以获取数组对应的流
- 根据Collection获取流:
new ArrayList<>().stream();
new HashSet<>().stream();
new Vector<>().stream(); - 根据Map获取流:
new HashMap<>().keySet().stream();
new HashMap<>().values().stream();
new HashMap<>().entrySet().stream(); - 根据数组获取流:
Stream.of(new String[5]);
常用方法:
- long count();统计个数(终结)
- void forEach(Consumer<? super T> action);逐一处理(终结)
- Stream filter (Predicate<? super T> predicate);过滤(函数拼接)
- Stream limit(long maxSize);取用前几个(函数拼接)
- Stream skip(long n);跳过前几个(函数拼接)
- Stream map(Function<? super T, ? extends R> mapper);映射(函数拼接)
- static Stream concat(Stream<? extends T> a, Stream<? extends T> b)组合,(函数拼接)
并发流:
- 转换为并发流: 流对象.parallel();
- 直接获取并发流: 集合对象.parallelStream();
- 使用并发流: 流对象.parallel().流方法
收集stream结果:
- 收集到集合中
方法:collect(Conllector<T,A,R>)
通过Collectors收集器工具类获得Conllector接口实例: public static Collector<T, ?, List> toList():转换为List集合。
使用: List list = 流对象.collect(Collectors.toList());
通过Collectors收集器工具类获得Conllector接口实例: public static Collector<T, ?, Set> toSet():转换为Set集合。
使用: Set set = 流对象.collect(Collectors.toSet());
- 收集到数组中
方法: Object[] toArray();
使用: Object[] objArray = stream.toArray(); - 解决泛型数组问题:
方法: < A > A[] toArray(IntFunction<A[]> generator);
使用: String[] strArray = 流对象.toArray(String[]::new);