美文网首页
java8 StreamApi 中间操作篇

java8 StreamApi 中间操作篇

作者: ChineseBoy | 来源:发表于2017-02-04 09:37 被阅读53次
    就如同流水线一样,多个中间操作形成一道流水线,但是只有执行了终止操作,中间的一系列操作才会一次性执行完,最终得出结果,这个过程可以称为“惰性求值”。

    相关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);
    } 
    

    相关文章

      网友评论

          本文标题:java8 StreamApi 中间操作篇

          本文链接:https://www.haomeiwen.com/subject/gasjittx.html