Java 8 (one) functional programming

Source: Internet
Author: User

Functional programming One, lambda expression one) how to distinguish a lambda expression
1Runnable noarguments = (), System.out.println ("Hello World"); 2 3ActionListener oneargument = event, System.out.println ("button clicked"); 4Runnable multistatement = () { 5System.out.print ("Hello");6SYSTEM.OUT.PRINTLN ("World");7 };8 9binaryoperator<long> add = (x, y), X +y;Ten  OneBinaryoperator<long> addexplicit = (long x, long y), x + y;

1) No parameters are indicated with an empty "()".

2) Only one parameter, the parentheses can be omitted, only the parameter name is written.

3) lambda The body of an expression can be not only an expression, but it can also be a block of code, using braces
({} or throw an exception to exit. Only one line of code lambda expressions can also use curly braces to clarify lambda
where the expression starts and ends.

4) lambda An expression can also represent a method that contains multiple parameters reading
Read lambda expression. Instead of adding two numbers, this line of code creates a function to calculate the result of the addition of the
two numbers. Variable add binaryoperator<long> but the line of code that adds two numbers.  

5) The parameter types in all LAMBDA expressions so far are inferred by the compiler. Of course it is.
However, it is sometimes better to explicitly declare the parameter type, and you need to enclose the argument in parentheses, with multiple arguments
The same is true of the situation.

6) method Reference: A handy way to invoke parameters in a lambda expression.

Such as:

Artist , Artist.getname ()// can be written artist:: GetName

Constructors have the same wording:

New Artist (name,nationlity) // can be written as New

Target Type refers to the type of context in which the LAMBDA expression resides. For example, the Lambda table
To a local variable, or to a method as a parameter, a local variable or a method parameter
The type of the number is the target type of the LAMBDA expression.

b) Reference value, not variable

An anonymous inner class needs to declare a variable as final when it needs to refer to a variable in its method.

This restriction is relaxed in Java 8 and can refer to a non-final variable, but the variable must be final on a fait accompli (the variable can only be assigned once,

If you try to assign a value to the variable multiple times and then reference it in a lambda expression, the compiler will give you an error.

This behavior also explains why the LAMDBA expression is a closure-------a block of code that contains free variables (variables that are not passed in and that are not defined in the method block).

c) Function interface

A function interface is an interface that has only one abstract method and is used as the type of a lambda expression.

IV) type inference

You can omit the types of all parameters in a lambda expression.

Unable to infer the type of error message:

1 Operator ' & #x002B; ' cannot is applied to Java.lang.Object, Java.lang.Object.
Flow (Stream)

Streams allow programmers to manipulate collections at a higher level.

A) from an external iteration to an internal iteration

Use the For loop to calculate the number of artists from London:

1 int count = 0; 2  for (Artist artist:allartists) {3if (Artist.isfrom ("London")) {4 count++ ; 5 }6 }

Problems with this type of code:

1. each iteration of the collection class requires a lot of boilerplate code to be written

2. The For loop is also cumbersome to run in parallel mode and needs to be modified for each for loop to be implemented.

3.for The boilerplate code of the loop blurs the meaning of the code, and the process
Sequencer must read the entire loop body to understand. If a single for loops, it's not a big deal, but the burden is heavy in the face of a huge code base full of
loops, especially nested loops.

In terms of the rationale behind it, for The loop is actually a syntactic sugar that encapsulates the iteration, Let's spend a little more time here,
See how it works. First call iterator iterator iterative process, which is iterator hasnext next
method to complete the iteration. Expanded code such as example 3-2 3-1 /span>

1 int count = 0; 2 iterator<artist> Iterator = allartists.iterator (); 3  while (Iterator.hasnext ()) {4 Artist Artist = iterator.next (); 5 if (Artist.isfrom ("London")) {6 count++; 7 }8 }

Internal iterations:

1 long count = allartists.stream ()2 . Filter (Artist-Artist.isfrom ("London")) 3 . Count ();

Stream is a tool that uses functional programming to perform complex operations on a collection class.

II) common flow operations

Lazy Evaluation Method: A method that describes steam only and ultimately does not produce a new collection.

Early Evaluation method: The method that will eventually generate the value from steam.

1.collect (ToList ())

This method generates a list of steam values and is an early evaluation operation.

// The Stream.of method generates a Stream using a set of initial values. 

2.map

Map converts the value in a stream to a new stream.

1 list<string> collected = Stream.of ("A", "B", "Hello")2//LAMBDA expression must be An example of a Function interface 3. Collect (ToList ()); 4 assertequals (aslist ("A", "B", "HELLO"), collected);

3.filter

Iterate through the data and examine the elements therein.

1 list<string> beginningwithnumbers2 = Stream.of ("A", "1abc", "ABC1")3  // must be predicate4 . Collect (ToList ());

4.flatmap

The FlatMap method can replace a value with a stream and then concatenate multiple streams into a stream

1 list<integer> together = Stream.of (Aslist (1, 2), Aslist (3, 4))2//  Must be function3. Collect (ToList ()); 4 assertequals (aslist (1, 2, 3, 4), together);

5.max and Min methods

1 list<track> tracks = Aslist (new track ("Bakai", 524),2new Track (" Violets for Your Furs ", 378),3new track (" Time Is ", 451)); 4 Track shortesttrack = tracks.stream ()5 . Min (comparator.comparing  Track.getlength ()))6. get (); 7 assertequals (Tracks.get (1), shortesttrack);

6. The Steam object can be obtained by invoking the stream method of list or set.

III) Element order

1) Order of occurrence

Testing is always done by:

1 list<integer> numbers = aslist (1, 2, 3, 4); 2 list<integer> sameorder = numbers.stream ()3. Collect (ToList ()); 4 assertequals (numbers, sameorder);

It is not guaranteed to pass every time:

1 New Hashset<> (Aslist (4, 3, 2, 1)); 2 list<integer> sameorder = numbers.stream ()3. Collect (ToList ()); 4 // This assertion can sometimes fail 5 assertequals (Aslist (4, 3, 2, 1), sameorder);

This can lead to unexpected results, such as when using parallel streams, the ForEach method does not guarantee that the element is
Processed sequentially . If you need to ensure sequential processing, you should use
Foreachordered method

IV) Collector

A common structure that generates complex values from a stream. Just pass it to the collect method, all
Flow can use it.

1) Convert to another collection

such as: ToList, Toset, tocollection

2) Convert to Value

Use the collector to let the stream generate a value, such as:

1  Public Optional<artist> Biggestgroup (stream<artist> artists) {2 function<artist,long> GetCount = artist, artist.getmembers (). Count (); 3 return Artists.collect (Maxby (Comparing (GetCount))); 4 }

3) Data chunking

Decomposed into two collections, the collector Partitioningby, which takes a stream and divides it into two parts, uses the predicate object to determine which part of an element to belong to, and returns a
Map to a list.

1  Public Map<boolean, list<artist>> Bandsandsolo (stream<artist> artists) {2return Artists.collect (Partitioningby (Artist- Artist.issolo ())); 3 }

4) Data grouping

1  Public Map<artist, list<album>> albumsbyartist (stream<album> albums) {2return Albums.collect (Groupingby (album- Album.getmainmusician ())); 3 }

5) string

The previous wording:

 1  StringBuilder builder = new  StringBuilder ("["  2  for   ( Artist artist:artists) { 3  if  ( Builder.length () > 1)  4  builder.append ( ","  5  String name = Artist.getname ();  6  builder.append (name);  7  } b  8  uilder.append ("]"  9  String result = builder.tostring (); 

Now the wording:

1 String result =2artists.stream ()3. Map (artist::getname)4 . Collect (Collectors.joining (",", "[", "]"));

6) Custom Collector

Not to be continued

Iii. overloading and inheritance one) overloading

1) When a LAMBDA expression is a parameter, its type is deduced by its target type , and the derivation process follows
The following rules:
1. If there is only one possible target type, it is deduced from the parameter type in the corresponding function interface;
2. If there are multiple possible target types, derive from the most specific type;
3. If there are multiple possible target types and the most specific type is ambiguous, the person will be the specified type.

2) Each interface used as a function interface should add a @functionalinterface comment that checks to see if the annotated interface conforms to the standard of the function interface.

III) inheritance

1) Default method

Introduce the default method purpose: Backward compatibility of the interface (if there is no default method, when we define a new method in the interface ...). )。

1. The default method can be used regardless of function interface or non-function interface.

2. At any time, the default method conflicts with the methods in the class, and the methods in the class are preferred.

3. Multiple inheritance, the class implementation of the interface has the method signature of the same default method, at this time the compiler will error:

1 class Musical Carriage 2  for Rock () from types Carriage and Jukebox.

Workaround: Override:

1  Public class Musicalcarriage 2 Implements Carriage, Jukebox {3@Override4 public String Rock () {  5return carriage. Super . Rock (); 6 }7 }
III) differences from abstract classes

There is still a noticeable difference between an interface and an abstract class. Interfaces allow multiple inheritance, but no member variables; abstract classes can be
To inherit member variables, but not multiple inheritance.

Iv. static method of the interface

If a method has sufficient semantic reasons to relate to a concept, then the method and related classes should be
or interfaces together, instead of being placed in another tool class. This helps to better organize the code and read the code for People
It is also easier to find relevant methods.

Java 8 (one) functional programming

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.