java8 StreamApi 中间操作篇

就如同流水线一样,多个中间操作形成一道流水线,但是只有执行了终止操作,中间的一系列操作才会一次性执行完,最终得出结果,这个过程可以称为“惰性求值”。

相关API介绍:

1. 筛选与切片
  • filter——接收 Lambda , 从流中排除某些元素。
  • limit——截断流,使其元素不超过给定数量。
  • skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  • distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    举个例子:

List<Person> pList = Arrays.asList( new Person("tom1",12,true), new Person("tom2",13,false), new Person("tom3",14,true), new Person("tom4",17,true), new Person("tom5",18,false), new Person("tom6",15,true), new Person("tom6",15,true), new Person("tom6",15,true) );

@Test
public void test1(){
    pList.stream()
         .filter(p->p.getAge() > 13)
         .limit(6)      //短路,只有找到俩条符合条件的,后面的迭代就不会在执行了
         .skip(1)
         .distinct()    //根据元素的hashcode和equals方式去重的
         .forEach(System.out::println);
}
2.映射
  • map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
  • mapToDouble:接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的DoubleStream。
  • mapToLong:接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的LongStream。
  • mapToInt:接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的IntStream。
  • flatmap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

看例子吧:

   @Test
public void test2(){
    List<String> strList = Arrays.asList("aa","bb","cc");
    strList.stream()
           .map((x)->x.toUpperCase())
           .forEach(System.out::println);

    pList.stream()
         .map(Person::getName)
         .forEach(System.out::println);
} 

@Test
public void test3(){
    List<String> strList = Arrays.asList("aa","bb","cc");
    strList.stream()
           .flatMap(StreamApi002::getChar)    //map是对元素进行操作,flatmap是对流进行操作
           .forEach(System.out::println);
           
}

public static Stream<Character> getChar(String str){
    List<Character> cList = new ArrayList<>();
    for (Character character : str.toCharArray()) {
        cList.add(character);
    }
    return cList.stream();
} 
3. 排序
  • sorted:自然排序(comparable)
  • sorted(Comparator<T>) :定制排序

例子时刻:

@Test
public void test4(){
    List<String> strList = Arrays.asList("dd","aa","bb","cc");
    strList.stream().sorted().forEach(System.out::println);
    strList.stream().sorted((s1,s2)->{
           return s1.compareTo(s2);
       }).forEach(System.out::println);
} 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • //Clojure入门教程: Clojure – Functional Programming for the J...
    葡萄喃喃呓语阅读 3,777评论 0 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 86.复合 Cases 共享相同代码块的多个switch 分支 分支可以合并, 写在分支后用逗号分开。如果任何模式...
    无沣阅读 1,443评论 1 5
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,778评论 18 399
  • 文/添一抹岚 终于想要提笔写写早与我们天人两隔的阿婆了。 之前就想着要写她,可常会觉得时候未到,总认为特定的景或情...
    添一抹岚阅读 829评论 69 54