Stream流

概述:
  “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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值