"The beauty of Java code"---Java8 Stream

Source: Internet
Author: User
Tags comparable stream api

Stream

The first time I saw the stream expression attracted me so much that it would make your code neater and the operation of the collection much more efficient, and if you haven't used the Java8 stream feature yet, then you're really out.

I. Overview1. What is Stream

Stream is a Data view that is available for streaming operations it is similar to the concept of a view in a database it does not change the source data collection If it changes the operation it will return a new data collection.

In general, it has three main features: After that we will follow the detailed instructions

1. Stream does not store data

2. Stream does not change the source data

3. Deferred execution characteristics of stream

2. Stream advantages
    1. The code is concise, the code written by functional programming is concise and explicit, and using the stream interface lets you say goodbye to the For loop.

    2. Multi-core-friendly, Java-functional programming makes it ever so easy to write parallel programs, all you need to do is call the parallel() method.

3. Stream API Common Methods
Stream Operation category
Intermediate operation (Intermediate operations) No status (stateless) Unordered () filter () map () Maptoint () Maptolong () maptodouble () FlatMap () Flatmaptoint () Flatmaptolong () Flatmaptodouble () Peek ()
Stateful (Stateful) Distinct () sorted () sorted () limit () Skip ()
End operation (Terminal operations) Non-short-circuit operation ForEach () foreachordered () ToArray () reduce () collect () max () min () count ()
Short-circuit operation (short-circuiting) AnyMatch () Allmatch () Nonematch () FindFirst () Findany ()

All operations on the stream fall into two categories: Intermediate and end operations , intermediate operations are just a token, and only the end operation will trigger the actual calculation.

Intermediate operations can also be divided into stateless and stateful:

A stateless intermediate operation means that the processing of an element is not affected by the preceding element, whereas a stateful intermediate operation must wait until all the elements have been processed before the final result is known, such as that the ordering is a stateful operation and the sorting result cannot be determined until all elements are read;

End operation can be divided into short-circuit operation and non-short-circuit operation

A short-circuit operation means that you can return a result without having to process all the elements, such as finding the first element that satisfies the condition. The reason for such fine partitioning is that the underlying approach to each case is different.

Common middleware

Filter: Filters The stream, filters the elements in the stream, and returns a qualified stream

map: Transforms a stream to convert one type of stream to another. (Maptoint, Maptolong, maptodouble returns the stream corresponding to int, long, double base type)

FlatMap: Simply put, one or more streams are merged into a new stream. (Flatmaptoint, Flatmaptolong, flatmaptodouble return the corresponding Intstream, Longstream, doublestream streams.) )

distinct: Go back to the heavy stream.

sorted: Returns a sorted stream.

Peek: used primarily to view the data state of an element in a stream.

Limit: Returns a stream consisting of the first n element data. is a short-circuit operation

Skip: Returns the stream that consists of the data behind the nth element.

End action

ForEach: Loops through the data in the stream.

ToArray: Returns the array object corresponding to the element in the stream.

reduce: aggregation operation, used to do statistics.

Collect: An aggregation operation that encapsulates the target data.

min, Max, Count: aggregation operation, minimum, maximum, total quantity.

anymatch: Short-circuit operation, with a qualified return of true.

Allmatch: All data is eligible to return true.

Nonematch: All data does not meet the criteria to return true.

FindFirst: Short-circuit operation, gets the first element.

findany: Short-circuit operation, gets either element.

foreachordered: The dark element sequence performs the loop operation.

Ii. Description of various cases

A few more examples, later forget can also come to find their own blog, haha.

First write a domain object

 Public class Person {        private  Integer  id;         Private String name;         Private String sex;         Private Integer age;         // provides get,set, and full parameter constructors }
1. Map Middleware Related examples
 Public classTestMap { Public Static voidMain (string[] args) {List<Person> persionlist =NewArraylist<person>(); Persionlist.add (NewPerson (1, "Zhang San", "Male", 8)); Persionlist.add (NewPerson (2, "little", "female", 2)); Persionlist.add (NewPerson (3, "John Doe", "male", 25)); Persionlist.add (NewPerson (4, "Harry", "female", 20)); Persionlist.add (NewPerson (5, "Zhao Liu", "male", 38)); Persionlist.add (NewPerson (6, "big", "male", 65)); //1. Only take out all the names in the collection to form a new collectionList<string> namelist=Persionlist.stream (). Map (Person::getname). Collect (Collectors.tolist ());        System.out.println (Namelist.tostring ()); //2. Only take out all the IDs in the collection to form a new collectionList<integer> idlist=Persionlist.stream (). Maptoint (Person::getid). Boxed (). Collect (Collectors.tolist ());        System.out.println (Idlist.tostring ()); //3, List to Map,key value of Id,value as Person objectMap<integer, person> personmap = Persionlist.stream (). Collect (Collectors.tomap (Person::getid, Person-Person ));          System.out.println (Personmap.tostring ()); //4, List to Map,key value of Id,value for nameMap<integer, string> namemap =Persionlist.stream (). Collect (Collectors.tomap (Person::getid, person::getname));             System.out.println (Namemap.tostring ()); }}

Operation Result:

is not before a few layers of the for loop to solve the problem, through the stream as long as a line of code can be resolved.

Note that if you list to map key is not unique, will be error, so if you are not sure whether your key is unique, you can change to the following:

Map<integer, string> map = Persionlist.stream (). Collect (                - key1)        );
2. Filter related examples
 Public classTestfilter { Public Static voidMain (string[] args) {List<Person> persionlist =NewArraylist<person>(); Persionlist.add (NewPerson (1, "Zhang San", "Male", 8)); Persionlist.add (NewPerson (2, "little", "female", 2)); Persionlist.add (NewPerson (3, "John Doe", "male", 25)); Persionlist.add (NewPerson (4, "Harry", "female", 8)); Persionlist.add (NewPerson (5, "Zhao Liu", "female", 25)); Persionlist.add (NewPerson (6, "big", "male", 65)); //1. Find the number of people older than 20 years        LongAge=persionlist.stream (). Filter (P->p.getage () >20). Count ();        System.out.println (age); //2. Find the number of men who are older than 20 years and genderList<person> Agelist=persionlist.stream (). Filter (P->p.getage () >20). Filter (p-> "Male". Equals (P.getsex ())). Collect (Collectors.tolist ());    System.out.println (Agelist.size ()); }    /** Operation Result: * 3 * 2*/}
3. Sorted related examples

For array examples

 Public classtestsort {string[] arr1= {"abc", "A", "BC", "ABCD"}; /*** Sort by character length*/@Test Public voidtestsorted1_ () {Arrays.stream (arr1). Sorted (comparator.comparing (String::length)). ForEach (System.out::        PRINTLN); //output: A, BC, ABC, ABCD    }    /*** Reverse * reversed (), java8 generic derivation problem, so if comparing inside a non-method reference lambda expression will not be able to directly use reversed () * Comparator.reverseorde R (): also used for flip order, to compare objects (the type within the stream must be comparable) * Comparator. Naturalorder (): Returns a natural sort comparer for comparing objects (the type within the stream must be comparable)*/@Test Public voidtestsorted2_ () {Arrays.stream (arr1). Sorted (Comparator.comparing (string::length). Reversed ()). ForEach (        System.out::p rintln); //output: ABCD, ABC, BC, aArrays.stream (arr1). Sorted (Comparator.reverseorder ()). ForEach (System.out::p rintln); //output: BC, ABCD, ABC, aArrays.stream (arr1). Sorted (Comparator.naturalorder ()). ForEach (System.out::p rintln); //output: A, ABC, ABCD, BC    }    /*** Sort by First letter * followed by string length*/@Test Public voidtestsorted3_ () {Arrays.stream (arr1). Sorted (Comparator.comparing ( This:: COM1). thencomparing (String::length)). ForEach (System.out::p rintln); }
//output: A, ABC, ABCD, BC Public Charcom1 (String x) {returnX.charat (0); }}

For collection examples

 Public classTestsort { Public Static voidMain (string[] args) {List<Person> persionlist =NewArraylist<person>(); Persionlist.add (NewPerson (1, "Zhang San", "Male", 8)); Persionlist.add (NewPerson (2, "little", "female", 2)); Persionlist.add (NewPerson (3, "John Doe", "male", 25)); Persionlist.add (NewPerson (4, "Harry", "female", 8)); Persionlist.add (NewPerson (5, "Zhao Liu", "female", 25)); Persionlist.add (NewPerson (6, "big", "male", 65)); //1. Find the youngest ageCollections.sort (Persionlist, (x, y)x.getage (). CompareTo (Y.getage ())); Integer Age= Persionlist.get (0). Getage (); System.out.println ("Minimum Age:" +Age ); //output: Minimum Age: 2//2. Find the youngest nameString name =Persionlist.stream (). Sorted (Comparator.comparingint (x-x.getage ()))        . FindFirst (). Get (). GetName (); System.out.println ("Minimum Age Name:" +name); //output: Minimum age name: Small    }}

The rest is not specifically written. After encountering special again to add inside.

Reference

1 . Follow the Java 8–stream API QuickStart

2. Stream of Java8

3. [Java Advanced Article] [Functional programming][java 8+ Stream API]

4. In-depth understanding of Java Stream Pipeline

think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Lieutenant Colonel "10"

"The beauty of Java code"---Java8 Stream

Related Article

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.