JAVA8 new feature functional programming lambda

Source: Internet
Author: User
Tags data structures instance method iterable java se

Cute I'm just a link Porter ~

JSR (Java specification Requests) 335 = lambda expression + Interface Improvement (default method) + bulk Data operation one, functional programming
Processing the code in the form of data processing, which means that the function can be assigned to a variable, passed to a function, etc., and the function is the first level of value
Examples of getting Started:

Import java.util.List;
public class Test1 {public
    String cleannames (list<string> listofnames) {
        StringBuffer sb = new Stringbuffe R ();
        You can only process the elements in the list sequentially, each time you perform a filter, transform, and reduce (join) for
        (int i = 0; i < listofnames.size (); i++) {
            if ( Listofnames.get (i). Length () > 1) {
                sb.append (capitalizestring (Listofnames.get (i))). Append (",");
            }
        Return sb.substring (0, Sb.length ()-1). ToString ();

    Public String capitalizestring (string s) {return
        s.substring (0, 1). toUpperCase () + s.substring (1, s.length ()); c14/>}
}

Scala/groovy/clojure is a programming language on the JVM platform that supports functional programming, and the following functions rewrite the code in the Scala language:

Val employees = List ("DSDs", "D", "Gghh", "Kmo");
Val result = Employees
. Filter (_.length () > 1)
. Map (_.capitalize)

Will filter, transform and aggregate three behavior separate, on the surface, the above code looks like first traversing the list to pick out all eligible elements to pass to Map,map then traverse and process the result from the filter, finally the processing results are passed to reduce,reduce and then traversal processing. Number of seemingly to go through a lot of traversal, but its specific implementation is not so, because it has "inertia", its specific implementation behavior and the above Java For-loop implementation of the Basic Agreement, but the function of more intuitive, more concise just. Static language VS Dynamic language: http://www.zhihu.com/question/19918532


Java Functional Programming (LAMBDA):
When we use anonymous inner classes to define different behaviors for an interface, the syntax is too redundant, and the lambda provides a more concise syntax.
-Functional Interface Functional interfaces
Each function object corresponds to an interface type. A functional interface can only have one abstract method, and the compiler will judge itself based on the structure of the interface (the process is not simply a count of the interface method, because the interface may also define a static or default method). API authors can also specify an interface as a functional interface through the @functionalinterface annotation, after which the compiler verifies that the interface satisfies the requirements of the functional interface.

Functional interfaces that already exist in JAVA SE 7, for example:
-Java.lang.Runnable
-Java.util.concurrent.Callable
-Java.util.Comparator
-Java.io.FileFilter

A new package java.util.function is added to JAVA SE 8 that includes commonly used functional interfaces, such as:
-Predicate<t>-Boolean test (T-T);
-Consumer<t>-void accept (T-T);
-Function<t, r>-R apply (T-t);
-Supplier<t>-T get ();

-Bifunction<t, U, r>-R apply (T T, u u);


Examples of lambda expressions:
X-> x+1
()-> {System.out.println ("Hello World");}

(int x, int y)-> {+ +; y--; return x+y;}

Function<integer, integer> func = (x, Integer y)-> x + y//wrong
Function<integer, integer> func = Integer x-> x + 1//wrong

A lambda expression can be assigned to the target type T if and only if all of the following conditions are met:
-T is a functional interface
-The parameters of the lambda expression and the method parameters of T correspond to one by one of the number and type
-The return value of the lambda expression is compatible with the method return value of T
-the exception thrown in a lambda expression and the method of T throws type want to be compatible
The parameter types of a lambda expression can be omitted from the target type.
Target Type context:
-Variable Declaration
-Assign Value
-Return statement
Public Runnable Printsth () {
Return ()-> {
System.out.println ("Sth");
};

}


Comparator<string> C;

c = (string s1, string s2)-> s1.comparetoignorecase (S2);


-Array initializers
New filefilter[] {
F-> f.exists (), F-> f.canread (), F-> f.getname (). StartsWith ("s")

}


-Parameters of methods and construction methods
list<person> PS = ...;
stream<string> names = Ps.stream (). Map (P-> p.getname ());
The parameters of the map are function<t, R>,p can derive T as person type from list<person>, and by stream<string> you can know that R is of type String, When the compiler cannot parse out the correct lambda type, you can:
1. Provide a display type for lambda parameters
2. Transform the lambda expression into Function<person, string>

3. Provide an actual type for generic parameter r, such as. <string>map (P->p.getname ())


-Lambda expression function body
-The conditional expression (. :)
-Transition expression
supplier<runnable> C = ()-> ()-> {System.out.println ("hi");
callable<integer> c = flag? (()->): (()-> 42);
Object o = ()-> {System.out.println ("hi"); Illegal
Object o = (Runnable) ()-> {System.out.println ("hi");

Lexical scopes:
The lambda does not introduce a new scope.
public class Hello {
Runnable r1 = ()-> {System.out.println (this);
Runnable r2 = ()-> {System.out.println (toString ());
Public String toString () {return ' Hello, World ';}
public static void Main (String ... args) {
New Hello (). R1.run ();
New Hello (). R2.run ();
}

}

Output:

Hello, World

Hello, World

A lambda can not mask local variables in its context, similar to the following:
int i = 0;
int sum = 0;
for (int i = 1; i < i + 1) {//There will be a compilation error because I have declared it outside of the for loop
sum + = i;
}

Variable capture:

Import java.util.function.Function;

public class Test3 {
	int sum = 0;
	Public Function m () {
		//int sum = 0;
		Function<integer, integer> func= i-> {sum + +; return sum + i;};
		sum++;
		return func;
	}
	
	public static void Main (string[] args) {
		Test3 t = new Test3 ();
		Function<integer, integer> func = T.M ();
		t = null;
		System.out.println (func.apply (9));
		System.out.println (t.sum);
	}


Output:11, 2

Function<integer, integer> func = T.M (); ++this.sum;

System.out.println (func.apply (9)); ++this.sum; This.sum+i;

A lambda can only capture effectively final local variables, that is, the dependent variables cannot be modified after capture or capture. If sum is a local variable of the M method, Func cannot modify the local variable because m exits the stack frame after execution. This also avoids causing race condition,in a NUTSHELL,LAMBDA expression to be closed to the value and open to the variable.

int sum = 0;
List.foreach (e-> {sum + = E.size ();}); Illegal, close over values
List<integer> alist = new list<> ();
List.foreach (e-> {alist.add (e);}); Legal, open over variables

A race condition occurs when two or over threads can access shared data and they try to change it in the same time. Because the thread scheduling algorithm can swap between threads at any time, you don ' t know the order in which the thread S'll attempt to access the shared data.

List.parallelstream (). ForEach (e-> {sum = e;}); With multiple threads at the same time, if sum is not immutable, it will cause race condition, so we need to provide synchronization or use volatile to avoid reading stale data.

http://www.lambdafaq.org/what-are-the-reasons-for-the-restriction-to-effective-immutability/

In a normal inner class, an instance retains a strong reference to its external class instance, which can often result in a memory leak. A lambda expression maintains a this reference only when it is useful to a class instance variable, as above Func saves a reference to an instance of TEST3.


Lambda shorthand form-method reference:
If the method we want to invoke has a name, we can call it directly.
-Static method Reference Classname::methodname
-instance method reference on an instance Instancereference::methodname
-instance method reference on superclass Super::methodname
-Instance methods on types refer to Classname::methodname, such as string::touppercase, syntax and static method references, and the compiler will make a decision based on the actual situation
-Construct method Reference Classname::new
-Array construction method referencing Typename[]::new

Import java.util.function.Function;
Import java.util.function.IntFunction;

public class Test3 {public
static void TypeRef () {
//public string toUpperCase ()
function<string, string > func = string::touppercase;
System.out.println (func.apply ("AAA"));

public static void Arrayref () {
intfunction<int[]> arrayint = int[]::new;
int[] Array = arrayint.apply (a);
SYSTEM.OUT.PRINTLN (array);

public static void Main (string[] args) {
typeRef ();
Arrayref ();
}

Default method and Static interface method
How to add other methods to a single abstract functional interface? Interface methods can be abstract and default, the default method has a default implementation, and the type of implementation interface can be inherited by the default implementation. In addition, the interface allows the definition of static methods so that we can directly invoke the auxiliary methods associated with it from the interface. The default method can be inherited, and when the superclass of the parent class and the interface has multiple methods with the same signature, such as diamond inheritance, we need to follow some rules:
1. The method of the class takes precedence over the default method, whether the method is concrete or abstract
2. Methods covered by other types are ignored when the superclass shares a common ancestor
Class Linkedlist<e> implements List<e>, queue<e> {...}
3. When two separate default methods or default methods and abstract methods conflict, there will be a compilation error, we need to explicitly override the superclass method
Interface Robot implements Artist, Gun {
default void Draw () {Artist.super.draw ();}
}


Third, batch processing

-Passing behavior rather than value

Enhanced for Loop VS ForEach

Import java.util.*;

Import Java.util.function.Consumer;

	public class Test2 {static list<integer> numbers = Arrays.aslist (1, 2, 3, 4, 5);
		public static void outer () {//can only process the element for (int number:numbers) {System.out.println (number) in the collection sequentially;

}//interface Consumer<t>://Void Accept (T-T); interface Iterable<t>://default void ForEach (CONSUMER&LT;? Super T> Action) {//Objects.requirenonn
Ull (action); for (t t:this) {//action.accept (t);//}//}//Array.aslist-> array$arraylist/ /Array$arraylist extends Abstractlist, Abstractlist implements list<e>//List extends Collection, Collection ext Ends Iterable//public void ForEach (consumer&lt. Super t> Action) {//Objects.requirenonnull (action);//For (T E:A) {//Action.accept (e);//}//} public static void inner () {Numbers.foreach (value-> System.out
	. println (value)); public static void Main (string[] args) {inner (); }
}

Personally, in this example, foreach is not more efficient than a for loop, and generally works when it is invoked under the parallel stream.
-can be processed in parallel, batch processing
The stream is the new key abstraction in the Java8 class library, defined in Java.util.stream. The operation of the stream can be assembled into an assembly line pipeline.

Stream characteristics:
1. Stream does not store values, stream elements from the data source (data structure, build function or I/O Channel)
2. The operation of the stream does not modify the data source
3. Lazy evaluation, each step as soon as one find the number to meet the conditions, immediately passed to the next step to deal with and suspend the current step
4. Optional upper bounds, because the stream can be infinite, and the user can read continuously until the upper bounds are set

We can use the collection as the data source for the stream (collection has the stream and the Parallelstream method), or we can generate a collection (collect method) through the stream. The stream's data source may be a mutable set, and if the data source is modified over time, a interference is generated, so as long as the collection belongs only to the current thread and the lambda expression does not modify the data source.
1. Do not interfere with the data source
2. Do not interfere with other lambda expressions, this interference occurs when a lambda modifies a mutable state while another lambda reads state

Inert:
Acute evaluation, that is, before the method return to complete the filtering of all elements, while the lazy evaluation is required to filter, a one-time traversal.

Collectors:
Use the Collect () method to aggregate the elements in the stream into the collection, such as list or set. Collect () receives a type collectors parameter that determines how the elements in the stream are aggregated into other data structures. The Collectors class contains factory methods for a large number of commonly used collectors, and ToList () and Toset () are the two most common.

Parallel:
In order to achieve efficient parallel computing, the Fork/join model is introduced:
-Break the problem into a child problem
-Serial resolution of child problems to achieve partial results
-Combined partial results as final results


Parallel flow: The abstraction of the stream as Spliterator allows the transfer of part of the input element to another new spliterator, while the remaining data is stored in the original spliterator. The two spliterator can then be further segmented. A split iterator can also provide metadata for the source (such as the number of elements) and a range of other Boolean characteristics (such as whether the element is sorted). If you want to implement a collection or stream yourself, you may need to implement the Spliterator interface manually. Stream is very important in the Java SE8, we provide the stream and Parallelstream for collection to convert the collection into a stream, and the array can be transformed into a stream by Arrays.stream (). There are also static factory methods in the stream to create the stream, such as Stream.of (), Stream.generate (), and so on.

-Create Stream
static method of 1.Stream interface
stream<integer> Integerstream = Stream.of (1, 2, 3, 5);
stream<string> StringStream = Stream.of ("Taobao");

The default method for 2.Collection interfaces


-Converts the stream, and each conversion returns a new stream object (converts a stream through certain actions into a new stream)
1. The elements contained in the Distinct,stream are not duplicated
2. Filter, using the given filter function for filtering operation
3. Map, for the elements contained in the stream using the given transformation function for the conversion operation, the newly generated stream contains only the transformation-generated elements. This method has three variants for the original type, namely Maptoint, Maptolong and maptodouble.
4. Peek, generate a new stream containing the elements of the original stream, while providing a consumption function that executes the given consumption function when each element of the new stream is consumed
5. Limit, truncation of a stream

6. Skip, return a drop of the first n elements of the original stream and the remaining elements to form a new stream


-Aggregates the stream to get the desired result
Accepts an element sequence as input, repeats a merge operation, and merges the elements of the sequence into a single summarized result

Http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html

Iv. Other

Code load Order:

Non-static is to request the memory space in new and initialize its value. Java must first load the bytecode, and then request the memory space of the class based on the byte code information by new. The static is loaded into the JVM by the byte code of the class, but only once. Static variables and static blocks of code are related to the declaration order, and if static variables are called in the code block today, the static variables must be declared before the static code block, and if the static code block does not call the static variable, then declare who is loaded.
Parent class static Property-"parent class static code block-" Subclass static variable-"subclass static code block-" Parent non-static variable-"Parent class non-static variable-" Parent non-static code block-"parent constructor-" Subclass Non-static Variable-"Subclass non-static code block-" subclass constructor

1. When the structure was initialized, the son of the late father
2. Static, Non-static
3. Classes in Java are loaded only when they are used
4. Java classes can be constructed as object instances only after the class bytecode is loaded


Recursive + combination study later again:

Http://www.cnblogs.com/ldp615/archive/2013/04/09/recursive-lambda-expressions-1.html

Http://www.kuqin.com/shuoit/20140913/342127.html


Currently (2016-8) like Jad,jd-gui do not support lambda features, so found a new decompile tool CFR, as long as the official website download CFR jar package, and then cmd command to enter the directory to place the package, run:

Java-jar Cfr**.jar *.class (* Number of places to write themselves according to the name)


Reference:1. Java Next Generation: Functional coding Style (Groovy, Scala and Clojure shared function structure and its advantages)
2. http://www.cnblogs.com/figure9/archive/2014/10/24/4048421.html
3. http://zh.lucida.me/blog/java-8-lambdas-insideout-library-features/

4. http://ifeve.com/stream/

5. http://www.oschina.net/question/2273217_217864

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.