zoukankan      html  css  js  c++  java
  • Java 8 中有趣的操作 Stream

    Stream

    不是java io中的stream

    对象创建

    我们没有必要使用一个迭代来创建对象,直接使用流就可以

    String[] strs = {"haha","hoho","lala"};
    List<String> names = Arrays.asList(strs);
    Stream<Person>stream = names.stream().map(Person::new);
    List<Person> personList = stream.collect(Collectors.toList());
    

    流使用起来代码更清晰

    long count = personList.stream().filter(p->p.getName().length()>10).count();
    

    流看上去有点像是集合,转换或者获取数据,不过有一定的差异性

    1. 流不会存储元素,,这些元素可能是 储存在底层的集合中,或者按需生成的
    2. 流的操作不会修改其数据源 比如filter会生成一个新的流
    3. 流的操作尽可能是惰性执行的

    创建:可以使用Collection接口的stream方法

    也可以使用静态方法Stream.of()

    Stream<String>namesStream = Stream.of("haha","hoho","lala");
    

    无限流

    因为流的操作尽可能是惰性的,我们因此可以操作无限流

    Stream <T> stream<T> generate(Supplier<T> s)
    

    如果我们希望得到一个新的流,并且需要前n个元素,我们就可以使用 limit方法

    namesStream.limit(2);
    

    丢弃前几个元素

    namesStream.skip(2)
    

    流之间的连接

    Stream.concat(stream1,stream2);
    

    去重复

    namesStream.distinct();
    

    甚至还提供了排序接口

    namesStream.sorted((s1,s2)->{return s1.length()-s2->length()});
    
    

    甚至在使用的时候帮助自己调试

    Stream.iterate(1.0,p->p*2).peek(e->System.out.println("Fetching"+e)).limit(20).toArray();
    
    

    terminal 操作

    max,min等等

    Optional<T> max(Comparator<? super T>comparator)
    
    

    返回的Optional有点类似于 C++ Boost中的optional,用于判断返回的结果是否有效

    结果返回

    stream.collect(Collectors.toList());
    stream.collect(Collectors.toSet());
    // 也有使用 toJoinning(", ")
    //foreach
    stream.forEach(System.out::println);
    //如果需要转化字符串
    stream.map(Object::toString);
    
    

    收集到映射表中

    //
    Map<Integer,String> idToName = people.collect(
    	Collectors.toMap(Person::getId,Person::getName)
    );
    Map<Integer,Person> idToPerson = people.collect(
    	Collectors.toMap(Person::getId,Function.identity())
    );
    
    

    groupBy

    //举一个java core中的例子
    Map<String,List<Locale>>countryToLocales = locales.collect(
    	Collectors.groupingBy(Locale::getCountry));
    
    

    下游收集器

    Map<String,List<Locale>>countryToLocales = locales.collect(
    	Collectors.groupingBy(Locale::getCountry,toSet()));
    
    
  • 相关阅读:
    linux的openfire运行日志配置经历
    基于Html5的兼容所有主流浏览器的在线视频播放器videoJs
    Eclipse下使用Fat Jar插件对源代码进行打包
    ubuntu下的openfire安装、配置、运行
    linux系统时间同步更新
    PRD产品需求文档概要
    oracle实现自动记录存储过程、自定义函数执行错误
    Oracler读取各种格式的相关日期格式
    linux中shell变量$#,$@,$0,$1,$2的含义解释
    Linux的五个查找命令
  • 原文地址:https://www.cnblogs.com/stdpain/p/10646910.html
Copyright © 2011-2022 走看看