Java 8 Stream API

来源:互联网 发布:只有我知双语未删减版 编辑:程序博客网 时间:2024/06/03 21:34

Java 8 Stream API

在学习Java8新特性的时候感觉很吃力,所以同以往一样,通过例子来学习StreamAPI

一.什么是流

这个流stream不同于输入输出流,可以把它想成一个’数据水流‘,Stream 就如同一个迭代器(Iterator),单向,不可往复,数据只能遍历一次,遍历过一次后即用尽了

二.具体例子代码

1.构造方法

@Test    public void test1(){        // 几种初始化Stream的方法               // 1.普通的Stream构造        Stream stream = Stream.of("1","2","hello");        //2.使用数组构造        String [] s = new String[]{"he","llo"};        Stream stream2 = Stream.of(s);        //3.使用Collection进行构造        List<String> list = new ArrayList<>(Arrays.asList(s));        list.stream();    }

2.操作类型

Intermediate:一个流可以后面跟随零个或多个 intermediate 操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历。

Terminal:一个流只能有一个 terminal 操作,当这个操作执行后,流就被使用“光”了,无法再被操作。所以这必定是流的最后一个操作。Terminal 操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个 side effect。

Intermediate:

map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered

Terminal:

forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator

Short-circuiting:

anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit

3.foreach操作

    @Test    public void test2(){        List<String> list = new ArrayList<>(Arrays.asList("1","2","hello"));        list.stream().forEach(System.out::println);;    }

4.Match操作

    @Test    public void test3(){        List<String> list = new ArrayList<>(Arrays.asList("hello","world","hello","java","hello","Stream"));        boolean y = list.stream()                        .anyMatch((x)->x.equals("hello"));//      .allMatch((x)->x.equals("hello"));  所有都匹配返回true//      .noneMatch((x)->x.equals("hello")); 。。        System.out.println(y);

5.map操作

    public void test4(){        List<String> list = new ArrayList<>(Arrays.asList("hello","world","hello","java","hello","Stream"));        //  可以理解为一个元素到另一个不同元素的转化 也就是映射        List<String> li = list.stream()                              .map(s->s.toUpperCase())                              .collect(Collectors.toList());            System.out.println(li.toString());    }

6.flatMap操作

//The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream. 一对多关系,扁平化的结果    @Test    public void test5(){        Stream<List<Integer>> inputStream = Stream.of(                 Arrays.asList(1),                 Arrays.asList(2, 3),                 Arrays.asList(4, 5, 6)                 );                List<Integer> list = inputStream.                flatMap((childList) -> childList.stream())                .collect(Collectors.toList());                ;                System.out.println(list);    }

最终 里面已经没有 List 了,都是直接的数字。

这里写图片描述

7.filter 和 sorted

    @Test    public void test6(){        List<people> list = new ArrayList<>();        list.add(new people("zhangsan",32));        list.add(new people("lisi",23));        list.add(new people("wangwu",14));        list.add(new people("zhaoliu",22));        list.add(new people("tianqi",77));        List l = list.stream()            .filter((s)-> s.age> 30)            //sorted 排序//          .sorted((a,b)->a.getAge().compareTo(b.getAge()))//          如同foreach语句 但是foreach语句是termimal 的 执行完之后不能有其他语句            .peek((e)->System.out.println(e))            .collect(Collectors.toList());    }

8.reduce limit 和skip

    @Test    public void test7(){    //这个方法的主要作用是把 Stream 元素组合起来。它可以提供一个起始值(种子),然后依照运算规则,和前面 Stream 的第一个、第二个、第 n 个元素组合(计算)。        int sum = Stream.of(1, 6, 3, 4).reduce(0, Integer::sum);//      limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素        List<String> s = Stream.of("Stringvalue","1","2","4").limit(3).collect(Collectors.toList());        System.out.println(s.toString());        Optional<Integer> x = Stream.of(5,2,4,6,3).reduce(Math::max);        System.out.println(x.orElse(-1));    }
原创粉丝点击