stream in java8

如果使用过scala,使用scala函数编程思想处理数据,那酸爽谁用谁知道。使用java老觉得不得劲,但java8借用了scala的思想,引入了函数编程思想,那就是stream,随后我们慢慢体验她的妙处。

Java Stream提供了提供了串行和并行两种类型的流,保持一致的接口,提供函数式编程方式,以管道方式提供Transformations和action(借用spark的概念),为Java语言的集合提供了现代语言提供的类似的高阶函数操作,简化和提高了Java集合的功能。

关于流和其它集合具体的区别,可以参照下面的列表:

  • 不存储数据。流是基于数据源的对象,它本身不存储数据元素,而是通过管道将数据源的元素传递给操作。
  • 函数式编程。流的操作不会修改数据源,例如filter不会将数据源中的数据删除。
  • 延迟操作。流的很多操作如filter,map等Transformations是延迟执行的,只有到action才会将操作顺序执行。
  • 可以解绑。对于无限数量的流,有些操作是可以在有限的时间完成的,比如limit(n) 或 findFirst(),这些操作可是实现"短路"(Short-circuiting),访问到有限的元素后就可以返回。
  • 纯消费。流的元素只能访问一次,类似Iterator,操作没有回头路,如果你想从头重新访问流的元素,对不起,你得重新生成一个新的流。

流的操作是以管道的方式串起来的。流管道包含一个数据源,接着包含零到N个Transformations(),最后以一个action结束。
.

stream数据源

Collection的stream()和parallelStream()方法

        List list = Arrays.asList(1,2,3);
        int max=list.stream()
                        .mapToInt(v->v)
                        .max().orElseThrow(NoSuchElementException::new);
        System.out.println(max);

Arrays.stream(Object[])

    int objectMax=Arrays.stream(new Integer[]{1,2,3})
                                .mapToInt(v->v)
                             .max().orElseThrow(NoSuchElementException::new);
        System.out.println(objectMax);

stream工厂静态方法

Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator)

        int max = Stream.of(1, 2, 3).mapToInt(v -> v).max().orElseThrow(NoSuchElementException::new);
        System.out.println(max);
        IntStream.range(1, 5).max().orElseThrow(NoSuchElementException::new);
        int seqMax = Stream.iterate(3, n -> n + 12).limit(10).mapToInt(v -> v).max().orElseThrow(NoSuchElementException::new);
        System.out.println(seqMax);

BufferedReader.lines() 和Files

package im.jacksu.collection;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * description
 *
 * @author s00368426
 * @version 1.0
 * @date 2018/1/29 8:07
 */
public class FileDemo
{
    public static void writeFile()
    {
        String fileName = "stream.txt";
        try
        {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
            out.write("Hello jack:");
            out.newLine();  //注意\n不一定在各种计算机上都能产生换行的效果
            out.write("My name is bob!\n");
            out.write("I like you and miss you.");
            out.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void readFile()
    {
        String fileName = "stream.txt";
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            String line = in.readLine();
            while (line != null)
            {
                System.out.println(line);
                line = in.readLine();
            }
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        writeFile();
        String fileName = "stream.txt";
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            in.lines().findFirst().ifPresent(System.out::println);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        /**
         * Files demo
         */
        Path path = Paths.get("./");
        try
        {
            Files.list(path).findFirst().ifPresent(System.out::println);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Random.ints()

    public static void main(String[] args)
    {
        Random random = new Random();
        random.ints(10,1,5).forEach(System.out::println);
    }

参考

Java 8 Stream Tutorial
Java 8 Stream探秘
Java Stream 详解
Package java.util.stream
Java 8 Stream 教程

你可能感兴趣的:(stream in java8)