How to use Stream to create flow in Java8
This article introduces how to use Stream to create streams in Java8. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.
First, from the Collection collection Stream stream = new HashSet ()
.stream ()
Stream stringStream = new ArrayList ()
.stream ()
Second, create a numerical stream IntStream intStream = IntStream.rangeClosed (1,100) according to the numerical range.
Third, from a series of values Stream provides a static method to generate a stream Stream integerStream = Stream.of (1, 2, 3) from a series of values
Stream stringStream = Stream.of ("like", "astronomy", "de", "pony", "stationmaster")
AppleStream apple = new AppleStream ()
Stream appleStream = Stream.of (apple, apple, apple)
IV. Support specific basic type streams from array / /
IntStream intStream = Arrays.stream (new int [] {1,2,3})
LongStream longStream = Arrays.stream (new long [] {1L, 2L, 3L})
DoubleStream doubleStream = Arrays.stream (new double [] {1D, 2D, 3D})
Stream stringStream = Arrays.stream (new String [] {"like", "astronomy", "de", "pony", "webmaster"})
AppleStream apple = new AppleStream ()
Stream appleStream = Arrays.stream (new AppleStream [] {apple, apple, apple})
5. Prepare documents from documents
Stream linesStream = Files.lines (Paths.get ("fileStream.txt"))
LinesStream.forEach (System.out::println)
Result
Sixth, the function to generate infinite flow Java8 provides Stream.iterate () and Stream.generate () to generate infinite flow, these two methods will generate infinite data based on the given expression of the stream, so generally combined with limit () to use. Iteration: Stream.iterate (T seed,Function apply) generation: Stream.generate (Supplier s) / / given an initial value seed, and a function `that receives an input parameter and returns a value `
Stream.iterate (10, x-> x + 5)
.limit (10)
.forEach (System.out::println)
Random random = new Random ()
/ / receive a function with no input parameter and return value `
Stream.generate (()-> random.nextInt)
.limit (10)
ForEach (System.out::println); this is all about how to use Stream to create streams in Java8. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.