Java8 new features Get started STREAM/LAMBDA

Source: Internet
Author: User
Tags first string stream api

Stream in Java 8 is an enhancement to the functionality of the collection (Collection) object, focusing on a variety of very convenient, efficient aggregation operations (aggregate operation) for collection objects, or large-volume data operations (bulk data operation )。 The Stream API greatly improves programming efficiency and program readability by using the same new LAMBDA expression. It also provides both serial and parallel modes for aggregation, and the concurrency pattern maximizes the benefits of multi-core processors

Stream is not a collection element, it is not a data structure, it does not hold it, it is about algorithms and computations, it is more like an advanced version of Iterator. Get a data source → data transformation → perform an operation to get the desired result, each time the original stream object is converted unchanged, a new stream object (which can have multiple conversions) is returned, which allows the operation to be arranged like a chain and become a pipe

Why not implement these operations in the collection class, but instead define a new stream API? Oracle has given several important reasons:

The first is that all the elements held by the collection class are stored in memory, and the very large collection class consumes a lot of memory, while the elements of the stream are computed at the time of access, and this "lazy" feature is somewhat similar to Clojure's lazy-seq, which consumes little memory.

The second is that the iteration logic of the collection class is the caller's responsibility, usually the for loop, and the stream iteration is implicit in the various operations on the stream, for example map() .

For the basic numerical type, there are currently three kinds of corresponding packaging types Stream:intstream, Longstream, Doublestream.


Stream is a big new API for JAVA8. Official definition: Supports feature-type operations on element flows, such as mapping to reduce conversions on a collection.

Characteristics:

Not stored. Instead of storing the data structure of the element, the data stream passes the element from the source data structure, array, generator function, or input/output channel to the pipeline of the calculation operation.

Functionality. A stream operation produces a result, but does not modify its source. For example, a data stream filtered from a collection produces a new stream without filtering the element, rather than removing it from the source collection.

Lazy seeking. Many flow operations, such as filtering, mapping, or removing duplicates, can be lazily, exposing the opportunity to optimize. For example, "Looking for the first string of three consecutive vowels" does not need to check all the input strings. Flow operations are divided into intermediate (flow production) operations and terminal (value or side-effect production) operations. Intermediate operations are always lazy.

may not be bounded. Although the collection has a finite size, the stream is not required. Short-circuit operations such as limit (n) or FindFirst () can allow infinite flow calculations to be completed within a limited time.

Flow but differs from I/O flow. Stream is an enhancement to the functionality of the collection (Collection) object, which focuses on a variety of very convenient, efficient aggregation operations (aggregate operation) for collection objects, or large-volume data operations (bulk data operation). The Stream API greatly improves programming efficiency and program readability by using the same new LAMBDA expression. It also provides both serial and parallel modes for aggregation, and the concurrency pattern leverages the benefits of multi-core processors to split tasks and accelerate processing using fork/join parallel methods. Writing parallel code is often difficult and error-prone, but using the Stream API makes it easy to write high-performance concurrent programs without having to write a single line of multithreaded code. So, the first java.util.stream in Java 8 is the product of a functional language + multi-core ERA synthesis effect.

Lambda Syntax:

(params), expression
(params)-statement
(params), {statements}


Key words:

Filter: is an intermediate operation that accepts a variable of the predicate interface type and filters the elements in all stream objects. Filter (S-s.getstate () ==state.pay)

Map: is an intermediate operation on a stream object that, given a method, can correspond each element of a stream object to another object. Map (S-s.getplanno ())/Map (Plan::p lanno)/price becomes 10 times times map (S-to S.getprice (). Multiply (Bigdecimal.valueo F (10)))

Reduce: Mix the Stream elements together. It provides a starting value (seed), and then according to the arithmetic rule (binaryoperator), returns a single result value, and the reduce operation always creates a new value for each element processed

BigDecimal total = Stream (). Reduce (Bigdecimal.zero, (a), A.add (b)); Or

BigDecimal total = Stream (). Reduce (Bigdecimal.zero, Bigdecimal::add)

Limit: Returns the first n elements of a Stream, and skip discards the top n elements

Sorted: An intermediate operation that returns a view of an ordered stream object. The elements in the stream object are sorted by default in natural order, unless you specify a comparator interface yourself to change the collation.


Collect: Modifying an existing value

The main function of the collectors class is to assist in various useful reduction operations.

Groupingby grouped by rules: Stream (). Collect (Collectors.groupingby (P->p.getstate ()))

Partitioningby is a special kind of groupingby that constructs the returned data structure according to whether two results of the condition test, get (true) and get (false) can be all element objects.


Stream has three match methods, semantically speaking:

All elements in Allmatch:stream conform to the incoming predicate and return True

Returns true if there is an element in the anymatch:stream that conforms to the incoming predicate

None of the elements in the Nonematch:stream conform to the incoming predicate, which returns true


example, domain

public class Plan {
private int id;
Private String Planno;
Private BigDecimal Price;
Private long total;
Private state State;
Private Calendar Createtime;
Private Jsonobject features = new Jsonobject ();

Sate:nopay (1, "unpaid"), Pay (2, "paid"), Settle (3, "settlement"),


list<plan> planlist = Initlist ();

1. Convert plan number Planno to uppercase return list

list<string> noList = Planlist.stream (). Map (P->p.getplanno (). toUpperCase ()). Collect (Collectors.tolist ()) ;


2, price from high to low sort

list<plan> list = Planlist.stream (). Sorted ((b) B.getprice (). CompareTo (A.getprice ())). Collect ( Collectors.tolist ());


3, the status for the paid price is sorted by high to low

Planlist.stream (). Filter (S-state.pay = = S.getstate ()). Sorted (A, B) B.getprice (). CompareTo (A.getprice ())) . Collect (Collectors.tolist ());

4, for high/low/Total price, total quantity average, sum

BigDecimal max = Planlist.stream (). Max ((b)->a.getprice (). CompareTo (B.getprice ())). Get (). GetPrice ();
BigDecimal min = Planlist.stream (). Min ((b)->a.getprice (). CompareTo (B.getprice ())). Get (). GetPrice ();
BigDecimal total = Planlist.stream (). Map (P->p.getprice ()). Reduce (Bigdecimal.zero, (a),->a.add (b));

Average: Planlist.stream (). Maptolong (Plan::gettotal). Average (). getasdouble ();

Sum: Planlist.stream (). Maptolong (plan::gettotal). SUM ()

5, total number of status values

Long Count = Planlist.stream (). Map (P->p.getstate ()). Distinct (). Count ();
Long C2 = Planlist.stream (). Map (P->p.getstate ()). Collect (Collectors.toset ()). Size ();


6, the scenario number contains some characters

list<plan> list = Planlist.stream (). Filter (P->p.getplanno (). Contains ("GT")). Collect (Collectors.tolist ()) ;


7, the price of the first three plan

List<plan> toplist = Planlist.stream (). Sorted ((b)->b.getprice (). CompareTo (A.getprice ())). Limit (3). Collect (Collectors.tolist ());


8, grouped by scenario status list

Map<state, list<plan>> map = Planlist.stream (). Collect (Collectors.groupingby (P->p.getstate ()));


9, the plan is divided into whether to pay two kinds, query list

Map<boolean, list<plan>> map = Planlist.stream (). Collect (Collectors.partitioningby (S-to s.getstate () = =state.nopay));

Map.get (TRUE) is not paid all

Map.get (FALSE) is the payment and settlement


10, convert to map structure < program number, price >

map<string, bigdecimal> map = Planlist.stream (). Collect (Collectors.tomap (P->p.getplanno (), Plan::getPrice) );


11, Convert data structure, list to array

Plan[] PS = Planlist.stream (). ToArray (plan[]::new);

12, sum/average of quantity by state

Average: map<state, double> Map = Planlist.stream (). Collect (Collectors.groupingby, Collectors.averaginglong (plan::gettotal));

Sum: map<state, long> sum = Planlist.stream (). Collect (Collectors.groupingby, Collectors.summinglong (plan::gettotal));


Map<state, longsummarystatistics> summap = Planlist.stream (). Collect (Collectors.groupingby, Collectors.summarizinglong (plan::gettotal));

Longsummarystatistics describes various summary data for elements in the stream, for Count, Min, Max, sum, and average.

Java8 new features Get started STREAM/LAMBDA

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.