java

        自java更新到jdk8后,添加了lambda表达式及java.util.Stream,以下便是对此进行说明
Stream对数据进行处理,但对原来的数据不进行更改

java创建stream的几种方法

        From a Collection via the stream() and parallelStream() methods

1
2


        From an array via Arrays.stream(Object[])

1
2
3
int[] array = {1, 2, 3, 4, 5}

Stream stream = Arrays.stream(array)

        From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator)

1
2
3
4
5
int[] array = {1, 2, 3, 4, 5}

Stream stream = Stream.of(array)

Stream stream = IntStream.range(3,9) //stream = {3, 4, 5, 6, 7, 8, 9}

        The lines of a file can be obtained from BufferedReader.lines()

1
2
3
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:\\tmdb_5000_movies2.json"));

Stream stream = bufferedReader.lines()

        Streams of file paths can be obtained from methods in Files

        Streams of random numbers can be obtained from Random.ints()

1
Random.ints().asLongStream()

        Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream()

filter

        对stream的对象内的内容进行对其内部的所有数据进行循环,过滤不符合条件的数据,不会带来副作用

1
2
3
4
5
int[] array = {1, 2, 3, 4, 5}

Stream stream = Stream.of(array)

stream.filter(e -> e / 2 == 0).forEach(System.out::println) // --> {2, 4}

map

        获得stream对象中的数据进行操作,对其内部的所有数据进行循环操作,若用它进行过滤,将会带来副作用,不仅能返回值,同时返回可过滤后的结果Boolean值

1
2
3
4
5
6
7
int[] array = {1, 2, 3, 4, 5}

Stream stream = Stream.of(array)

stream.filter(e -> e / 2 == 0)
.map(e -> e*2)
.forEach(System.out::println) // --> {4, 8}

reduce

        该函数处于stream终端,用了reduce函数后不可再用stream的其他方法,若需要使用stream的方法时需要重新stream化.
        在java8中reduce方法重载有三个,三个方法中的参数数量不同

1
2
3
4
5
6
7
# supplier为reduce方法开始的参数,同时决定着返回值的类型
# 当stream为并行化时才会调用combiner
stream.parallel().reduce(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)

stream.reduce(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)

stream.reduce(BiConsumer<R, ? super T> accumulator)

        
        

1
2
3
stream.filter(e -> e / 2 == 0)
.map(e -> e*2)
.reduce()

javaScript

iterator

iterable

× 请我吃糖~
打赏二维码