In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what is the role of Java8 Stream API". In daily operation, I believe that many people have doubts about the role of Java8 Stream API. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is the use of Java8 Stream API?" Next, please follow the editor to study!
Stream API action
Created for collection, simplify collection operation and support collection concurrent operation.
From iterator to StreamString contents = new String (Files.readAllBytes (Paths.get (alice.txt)), StandardCharsets.UTF_8); List words = Arrays.asList (contents.split ("[\ P {L}] +")); iterator int count = 0 for (String w: words) {if (w.length () > 12) count++;} Streamlong count = words.stream (). Filter (w-> w.length () > 12). Count () / / concurrency statistics is easy. You only need to replace stream () with parallelStream () as follows: long count = words.parallelStream (). Filter (w-> w.length () > 12). Count (); the difference between Stream and collection
Stream itself does not store elements, which are stored in the underlying collection or generated as needed
The Stream operator does not change the source Stream object, it returns a new Stream object that holds the result
Stream operators may be deferred, which means they wait until the results are needed. For example, if only the first five long words are needed, the filter method will stop filtering after the fifth match.
Stream usage process
Create a Stream (data structures from collections, arrays, iterators, generators, etc.)
Convert the initial Stream to another Stream through one or more Stream operators
Use a Stream termination operator to produce a result that forces its previous operation to be performed immediately, after which the Stream will no longer be used.
Create Stream
Collection: the stream () method of Collection, which produces a Stream object
Array: Stream.of (T... Values) accepts a list of variable-length parameters, which can be an array or multiple independent elements of the same type, resulting in a Stream object
Arrays.stream (array, from, to) converts part of an array to Stream
Empty Stream:Stream silence = Stream.empty ()
Unlimited Stream:
Stream echos = Stream.generate (()-> "Echo")
Stream randoms = Stream.generate (Math::random)
Stream integers = Stream.iterate (BigInteger.ZERO, n-> n.add (BigInteger.ONE))
JDK example:
Stream words = Pattern.compile ("[\\ P {L}] +") .splitAsStream (contents)
Stream lines = Files.lines (path)
Operate Stream common Stream operation functions
Filter: filter elements and produce a new Stream object
Map: conversion
FlatMap: one-to-many transformation, that is, the structure of each element map is another Stream, eventually merging all Stream into a single Stream
Example / / filter: get only long words List wordList =...; Stream words = wordList.stream (); Stream longWords = words.filter (w-> w.length () > 12); / / map: convert all words to lowercase Stream lowercaseWords = words.map (w-> w.toLowerCase ()); / / or use method reference Stream lowercaseWords = words.map (String::toLowerCase ()) / / get the initials of each word Stream firstChars = words.map (w-> w.charAt (0)); / / flatMap: get the letters Stream letters = words.flatMap (w-> Arrays.stream (s.toCharArray () in each word; Stream extraction and combination
Stream.limit (n), which returns a new Stream containing the first n elements of the source Stream, and the first m elements if the source Stream length m is less than n
Stream.skip (n), discard the first n elements of the source Stream and return a new Stream containing the remaining elements
Combine two Stream into a new Stream, assuming that stream1 and stream2 are Stream:Stream combined = Stream.concat (stream1, stream2) of two Character.
Stream.peek (action) produces another Stream with the same elements as the source Stream, but when each element is fetched, the function specified by the action parameter is called for ease of debugging.
Stream stateful transition
Stream's filter and map, flatMap and other operations are stateless transitions, because there is no need to consider previously converted elements when transforming each element.
The distinct operation of Stream returns a new Stream with no repeating elements in the same order based on the elements in the source Stream, which is a stateful transition because it needs to check whether the element has been read before when converting each element.
Stream aggregation operation
Stream's aggregation operation aggregates Stream into a value for use in programs, such as Stream.count (), Stream.max (), Stream.min (), Stream.findFirst (), Stream.findAny (), and so on.
The aggregation method is a termination operation, and the stream is closed after execution, and no other operations can be applied.
Example of aggregation operation: Optional longest = words.max (String::compareToIgnoreCase); if (longest.isPresent ()) {Sysout.out.println (longest.get ());} Optional startWithQ = words.filter (s-> s.startsWith ("Q")). FindFirst (); / / improve execution efficiency in parallel Optional startWithQ = words.parallel (). Filter (s-> s.startsWith ("Q"). FindAny () / / improve execution efficiency in parallel Optional startWithQ = words.parallel () .anyMatch (s-> s.startsWith ("Q")); terminate Stream
After a Stream object performs a termination operation, it cannot perform any other operations.
Optional Typ
An Optional object is an encapsulation of a T-type object, or means it is not any object.
The Optional class itself is very simple to implement, and the common operations are:
Of (T value)
OfNullable (T value)
IsPresent ()
IfPresent (consumer)
OrElse (T other)
OrElseGet (Supplier other)
Map (Function mapper)
FlatMap (Function mapper) is used to combine optional functions. For example, if f () returns Optional,T and has a method g () that returns Optional, it can be combined to call: Optional op = f (). FlatMap (Optional)
Usage and the rest of the source code is the most intuitive.
Stream aggregation operation
Aggregation, that is, the elements in Stream are aggregated into a value, such as summation, quadrature, counting, string appending, maximum, minimum, co-product, cross-product, etc. As long as there is an operation op between the operands x _ op _ y _ z, satisfying (x op y) op z = x op (y op z), then the op operation is aggregable.
Aggregate example / / summation Stream values =...; Optional sum = values.reduce ((x, y)-> x + y); / / if there is an identification e such that e op x = x, then the identification e can be used as the starting point for calculation. For addition, 0 is the identity, so there is another form: Optional sum = values.reduce (0, (x, y)-> x + y). / / or Optional sum = values.reduce (0, Integer::sum); / / find the total length of all strings in the string Stream Stream words =...; Optional sum = words.reduce (0, (total, word)-> total + word.length (), (total1, total2)-> total1 + total2); / / the second parameter accumulator is for aggregate calculation / / the third parameter, combiner, is to reaggregate the parallel results after parallel aggregate computing; Stream collects the results
After the stream processing is complete, we have two uses for the processing results:
Perform an aggregation operation to aggregate the entire Stream into a single value, such as sum, count, max, min, etc.
Collect Stream processing results, get each element in Stream, or print, or dump, or perform other calculations
The second type of "collecting Stream processing results" consists of two operations:
Collect, in two ways:
R collect (Collector
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.