Java Stream 8 generates the posture

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_36438618/article/details/102764667

Definition Stream

  • Polymeric supports sequential and parallel operation element sequence
  • It can be converted by the array, and a set of files from
  • Stream will not finish after consumption, and wanted the same water
  • Generating a stream of "source" does not change during operation a stream

Generating a stream of "gesture"

  • Generating a stream array
Integer[] arr = {1, 2, 3, 4, 6};//这里可以开成int[] 试试看看结果。。。①
        Stream.of(arr)//生成流Stream<Integer>
                .forEach(System.out::println);//打印流中的每个元素
  • Set (list) generating a stream, a stream Collection Interface method has been added, changed, all implementations of interfaces can be generated stream
Arrays.asList(1, 2, 3, 4)//返回list集合
                .stream()//转换为Stream<Integer>
                .forEach(System.out::println);
  • Read file generation flow
Files.lines(Paths.get("E:\\temp\\test.txt"))
                .forEach(System.out::println);
  • Stream flow comes to generate infinite, Stream class has two static methods to generate an infinite stream
    • Method Signature: public static Stream generate (Supplier s); Supplier is a function interface, the role of the main elements of the production stream
Stream.generate(() -> 1)
                .limit(5)// 
                .forEach(System.out::println);
  • Method Signature: public static Stream iterate (final T seed, final UnaryOperator f); seed is an initial value, UnaryOperator parameters passed in the operation parameters and the same return type
Stream.iterate(5, i -> i + 1)//生成无线流
                .limit(5)//使用limit 截断流 这里取前5个,类比sql 的limit
                .forEach(System.out::println);

The above two methods are generated infinite stream, the following two terms to generate a limited flow

  • LongStream IntStream and the range () and rangeClosed () method, two methods are the same parameters: start and end values, or types are long int, the difference between these two methods are: range not including the end of the method value, rangeClosed containing end value.
@Test
    public void streamRanged() {
        IntStream.range(1, 2)
                .forEach(System.out::println);
    }

result:

 1
    @Test
    public void streamRangeClosed() {
        IntStream.rangeClosed(1, 2)
                .forEach(System.out::println);
    }

result:

1
2

We welcome criticism correction
code address

Guess you like

Origin blog.csdn.net/qq_36438618/article/details/102764667