Stream is created in a number of ways, in addition to the most common collection creation, there are several other ways.
List Goto Stream
The list inherits from the collection interface, and collection provides the stream () method.
List<Integer> list = Lists.newArrayList(123);Stream<Integer> stream = list.stream();
Array Goto Stream
For arrays, arrays provides the stream () method.
new String[]{"a""b""c"};Stream<String> stream = Arrays.stream(arr);
Map Goto Stream
Map is not a sequence, it is not a collection, and there is no way to go directly to stream (). But EntrySet () is set and can be turned
Map<String, Object> map = Maps.newHashMap();Stream<Entry<String, Object>> stream = map.entrySet().stream();
Create stream directly
Stream also provides an API to generate a stream directly, which can probably be understood as a list. Because the inside is an array implementation.
Stream<Integer> integerStream = Stream.of(123);
Read the stream of a file
The use of Linux will be the command line of the pipe to admire unceasingly, a pipe symbol can be continuously processed. Reading files in Java can also achieve similar functionality.
long0;try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) { uniqueWords = lines.flatMap(l -> Arrays.stream(l.split(" "))) .distinct() .countcatch (IOException e) { //}
To generate an infinite stream through a function
Stream provides a iterate to generate an infinite sequence, an infinite sequence based on an initial value. You can use lambda to set generation rules for a sequence, such as adding 2 each time.
Stream.iterate(02) .limit(10) .forEach(System.out::println);
Another example is the Fibonacci sequence (Fibonacci sequence)
Stream.iterate(newint[]{01newint[]{t[1], t[0] + t[1]}) .limit(20) .map(t -> t[0]) .forEach(System.out::println);
Stream also provides another generate method to generate the sequence. Receives a user-specified build sequence function, Intsupplier.
Intsupplier fib =New Intsupplier() {Private intPrevious =0;Private intCurrent =1;@Override Public int Getasint() {intOldprevious = This.previous;intNextValue = This.previous+ This. Current; This.previous= This. Current; This. Current= NextValue;returnoldprevious; }};intstream.Generate(FIB).Limit(Ten).ForEach(System. out::p rintln);
java8-How to build a stream