Streams explanation of Java 8

Source: Internet
Author: User

Basic concepts of streams commentary in Java 8
The new collection streams operation in Java 8 simplifies the traversal set operation Behavior we display, and provides built-in concurrency capabilities . streams operation, if the operation produces a result orStreamis a lazy operation,But if it turns out void or other value values are eager operation , the purpose of thelazy operation is to Operational Efficiency. The lazy Operation in the Streams API is similar to our common builder pattern, which we used to set the properties of the class, where we set the behavior.
code Example:
Package Com.doctor.stream;import Java.util.list;import Java.util.stream.collectors;import com.google.common.collect.lists;/** * @author sdcuike * * Created on June 10, 2016 PM 4:29:32 * * It ' s very E Asy to whether a operation is eager or lazy:look at what it returns. * If It gives a Stream, it ' s lazy; If it gives another value or void, then it's * eager. This makes sense because the preferred by using these methods is to form a * sequence of lazy operations chain Ed together and then to has a single eager operation * At the end of that generates your result. * * This whole approach are somewhat similar to the familiar builder pattern.         In the builder * pattern, there is a sequence of calls that set up properties or configuration, followed * By a single call to a build method. The object being created isn ' t created until the call * to build occurs * * I ' m sure you ' re askING, "why would we want to having the differentiator between lazy and * eager options?" By waiting until we know more on what result and operations is * needed, we can perform the computations more efficiently. */public class Streamdemo {public static void main (string[] args) {list<string> names = Lists.newarrayli        St ("Doctor", "Lily", "who", "Doctor");            list<string> result = Names.stream (). Filter (E, {System.out.println ("Filter 1:" + e);        Return E.startswith ("do");            }). Filter (E, {System.out.println ("Filter 2:" + E);        Return E.startswith ("Doctor");        }). Collect (Collectors.tolist ());    SYSTEM.OUT.PRINTLN ("Result:" + result); }}

Execution Result:
Filter 1:d octorfilter 2:d octorfilter 1:lilyfilter 1:whofilter 1:d octor whofilter 2:d octor Whoresult:[doctor, Doctor Who

By the execution of the results, we can see thatthe filter operation of the streams isLazy operation, while the collect operation is eager operation.



Basic Operations1.collect (ToList ())This action is eager operation, which produces some type of numeric list from the stream.
list<string> list = Stream.of ("A", "B", "C"). Collect (Collectors.tolist ());        Boolean equals = Arrays.aslist ("A", "B", "C"). Equals (list);        Preconditions.checkstate (equals); True

2.mapwe often need to convert data from one form to another, and map operations can apply this function to data in the stream, resulting in a stream of data containing the new value.

list<string> mapoperation = Stream.of ("A", "B", "Doctor Who"). Map (String::touppercase). Collect ( Collectors.tolist ());        Preconditions.checkstate (Arrays.aslist ("A", "B", "DOCTOR who"). Equals (mapoperation));

3.filterrefer to the previous code example. The function of filtering data in the data stream is the same as before we write the If condition judgment function.
4.flatMapmap operation, as we've seen before, it transforms the data in the stream from one type to the other (non-stream type), but if we turn the data in the stream into what the stream does, we use the FLATMAP operation, which merges the resulting stream into one stream to continue the operation below.
  FlatMap lets you replace a value with a Stream and concatenates all the streams together.        list<integer> flatmapoperation = Stream.of (Arrays.aslist (1, 2), Arrays.aslist (3, 4)). FlatMap (E-, E.stream ()) . Collect (Collectors.tolist ());        Preconditions.checkstate (Arrays.aslist (1, 2, 3, 4). Equals (flatmapoperation));

5.max and MinThis operation is easy to understand, which is to find the maximum and minimum values in the list data.

   Integer max = Stream.of (1, 2, $). Max (Integer::compareto). get ();        Preconditions.checkstate (Max.equals (66));

6.reduce

When you want to get unique results from the data processing in the collection, we use the reduce operation.

int intvalue = Stream.of (1, 2, 3). Reduce (0, (ACC, E), ACC + e). Intvalue ();        Preconditions.checkstate (intvalue = = 6);


Take a look at the description of the Java doc:
Open Declaration integer java.util.stream.Stream.reduce (integer identity, binaryoperator<integer> accumulator) Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation fun Ction, and returns the reduced value.     This is equivalent to:t result = identity;  For (T element:this stream) result = accumulator.apply (result, Element) return result;but was not constrained To execute sequentially. The identity value must is an identity for the accumulator function. This means-for-all T, accumulator.apply (identity, T) are equal to T. The accumulator function must is an associative function. This is a terminal operation. Parameters:identity the identity value for the accumulating functionaccumulator an associative, non-interfering, stateles s function for combining valuesreturns:the result of the reduction@apinotesum, Min, Max, average, and string Concatena tion is all special cases of reduction. Summing a Stream of numbers can be expressed as:integer sum = integers.reduce (0, (A, b) a+b); Or:integer sum = integers.reduce (0, Integer::sum);  While this could seem a more roundabout-perform an aggregation compared-simply mutating a running total in a loop, Reduction operations parallelize more gracefully, without needing additional synchronization and with greatly reduced RIS K of data races.


Streams explanation of Java 8

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.