java8 笔记

来源:互联网 发布:怎样注销手机淘宝账号 编辑:程序博客网 时间:2024/05/18 01:36

Stream

流的组成

A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

流管道有一个源(可以是数组,集合,生成器,或者I/O管道等),0个或者多个中间操作(将一个流转换成另外一个流,例如:filter(Predicate))和一个终止操作(产生一个结果或者副作用,例如count()或者 forEach(Consumer))。流是惰性的,只有当执行了一个终止操作,源数据的计算才会被执行。

流由三部分组成:

  • 中间操作
  • 终止操作

流的创建

流的常见创建方式:

  • 通过Stream的of静态方法创建
  • 通过数组创建
  • 过集合创建
public class StreamTest {    public static void main(String[] args) {        // 1. 通过Stream的of静态方法创建        Stream stream = Stream.of("hello", "welcome", "to", "java8");        // 2. 通过数组创建        String[] array = new String[]{"hello", "welcome", "to", "java8"};        Stream stream1 = Stream.of(array);        Stream stream2 = Arrays.stream(array);        // 3. 通过集合创建        List<String> list = Arrays.asList("hello", "welcome", "to", "java8");        Stream stream3 = list.stream();    }}

流的简单应用

IntStream

https://www.leveluplunch.com/java/examples/java-util-stream-intstream-example/

  • builder

例:创建一个IntStream,然后添加上两个int值,最后求和

public class StreamTest {    public static void main(String[] args) {        int sum = IntStream.builder().add(10).add(10).build().sum();        System.out.println(sum);    }}输出:20
  • generate

例:生成5个随机数,然后迭代打印

public class StreamTest {    public static void main(String[] args) {        IntStream.generate(() -> {            return new SecureRandom().nextInt(20);        }).limit(5).forEach(System.out::println);    }}输出:结果是随机的754014
  • range

例:生成1到5之间的整数,包括1,不包括5(包括5可以用rangeClosed)

public class StreamTest {    public static void main(String[] args) {        IntStream.range(1, 5).forEach(System.out::println);    }}输出:1234
  • map and reduce

例:1-4 分别乘以 2 再求和

public class StreamTest {    public static void main(String[] args) {        int summary = IntStream.range(1, 5).map(num-> num * 2).reduce(0,Integer::sum);        System.out.println(summary);    }}输出:20
原创粉丝点击