JAVA8 new Features
Before learning JAVA8 Lambda, you must first understand the new features associated with Lambda in JAVA8, or you may feel unfamiliar with some concepts.
1, the default method and static method of the interface
Java 8 allows us to add a default method to the interface, which can be modified with default. The default method can be overridden.
Public interface IMyInterface {
void Onmethond (String str);//This is an abstract method
default String Ondefalutmethod () {// This is a default method return
"This is a default method";
}
Overriding default method public
class MyImpl1 implements IMyInterface {
@Override public
void Onmethond (String str) {
TODO auto-generated methods stub
}
@Override public
String Ondefalutmethod () {return
"override default Method"; c15/>}
///Do not override default method public
class MyImpl2 implements IMyInterface {
@Override public
Void Onmethond (String str) {
//TODO auto-generated method stub
}
}
In addition, Java 8 allows us to add a static method to the interface, which can be decorated with static.
Public interface IMyInterface {
void Onmethond (String str);//This is an abstract method
default String Ondefalutmethod () {// This is a default method return
"This is a default method";
}
Static String Onstaticmethod () {return
"This is a static method";
}
}
2. Functional interface (functional Interface)
What is called a functional interface. What's the difference between him and the normal interface?
A "Functional interface" is an interface that contains only an abstract method (which can contain both default and static methods), with no difference between other features and normal interfaces, and runnalbe,callable in Java is a functional interface; We can add @functionalinterface annotations to a function-compliant interface so that the interface is explicitly indicated as a functional interface, and if not, the compiler prompts the error directly. Of course, you can also not add this annotation. The benefit of adding is that because lambda expressions only support functional interfaces, if this interface is applied to lambda expressions, one day you accidentally add an abstract method, and the compiler prompts for an error.
Explicitly indicates that the interface is a functional interface
@FunctionalInterface public
interface IMyInterface {
void Onmethond (String str); This is an abstract method, default
String Ondefalutmethod () {//This is a default method return
"This is a default method";
}
Static String Onstaticmethod () {return
"This is a static method";
}
}
3, method and constructor reference
Java 8 allows you to use:: Keyword to refer to a method or constructor that already has a Java class or object. : The birth and the lambda are all to simplify the writing of anonymous inner classes, so:: Must be used in conjunction with functional interfaces. Using:: operator, will return a function interface object, this interface can be defined by itself, can also directly use the system provided by the functional interface, the system provided by the following will be described separately.
If there is a person class like this, the following examples are explained based on this class.
public class Person {
private String name;
private int age;
Public person () {
} public person
(String name,int age) {
this.name=name;
this.age=age;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
public int getage () {return age
;
}
public void Setage (int age) {
this.age = age;
}
public static String Show (String str) {
System.out.println ("-----> Input" +str);
Return "-----> Back" +str
}
}
Use:: keyword to initialize constructor, return a functional interface, this interface can be defined by itself, or directly using the function interface provided by the system. Now let's define a functional interface to get the person instance.
@FunctionalInterface Public
interface Personsupply {person get
();
}
Then write an implementation of the interface, if the usual way, the written code will generally be the following form.
personsupply sp=new personsupply{Public person get
() {person
person=new person ();
return person;
}
Person Person=sp.get ()//Get instance
Since JAVA8 introduced:: After the keyword, it can be simplified to a line of code, simply not too concise.
Personsupply sp=person::new; interface to implement person
person=sp.get ()//Get instance
Of course, in order to make this interface more general, we can define the following form
@FunctionalInterface Public
interface personsupply<t> {
T get ();
}
Personsupply<person> sp=person::new;
Person Person=sp.get ();
JAVA8 supplier interface is implemented in this way, will be introduced later. The direct use of supplier is as follows
Supplier<person> sp=person::new;
Person Person=sp.get ();
This simple notation also supports the parameter constructor, which first writes a functional interface, which, because of the need for parameters, enters the parameters in the Get () and returns the person, as follows.
@FunctionalInterface public
Interface Personsupply<p extends person> {
P get (String name, int age);
The general wording is as follows:
personsupply<person> sp=new personsupply<person>{Public person get
(String name, int age);
Person Person=new person (name,age);
return person;
}
Person Person=sp.get ("Maplejaw", 20);
The simple wording is as follows:
Personsupply<person> sp=person::new;
Person Person=sp.get ("Maplejaw", 20);
Using:: Keyword reference static method
Similarly, write a functional interface that requires parameters, so that the get () pass in the argument and return the argument, so return string.
@FunctionalInterface Public
interface Personfactory {
string-get (String str);
}
Personfactory pf=person::show;
Pf.get ("hahaha");
Personfactory pf=person::show; equivalent to the following
Personfactory pf=new personfactory{public
String get (String str) {return
person.show (str);
}
Use:: keyword refers to the common method is more special.
If the method to be invoked has no arguments, it can be invoked in class::method form, but you need to pass in a person instance, where the function interface writes, passing an instance of the person class in Get () and returning a string.
@FunctionalInterface Public
interface Personfactory {
String get (person);
}
Personsupply<person> sp=person::new;
Person Person=sp.get ("Maplejaw");
Personfactory Pf=person::getname;
SYSTEM.OUT.PRINTLN ("--->" +pf.get (person));
Personfactory Pf=person::getname; equivalent to the following
Personfactory pf=new personfactory{public String get (person person
) {return
person.getname ();
}
}
can also be called in instance::method form. The get () does not need to be passed in at this time. Returns a string.
@FunctionalInterface Public
interface Personfactory {
String get ();
}
Personsupply<person> sp=person::new;
Person Person=sp.get ("Maplejaw");
Personfactory Pf=person::getname;
SYSTEM.OUT.PRINTLN ("--->" +pf.get ());
Personfactory Pf=person::getname; equivalent to the following
Person Person=new person ("Maplejaw");
Personfactory pf=new personfactory{public
String get () {return
person.getname ();
}
}
If the method to be invoked has parameters, it must be called in instance::method form, when the function interface writes, and the set passes in the argument.
@FunctionalInterface Public
interface Personfactory {
void set (String name);
}
Personsupply<person> sp=person::new;
Person Person=sp.get ("Maplejaw");
Personfactory Pf=person::setname;
Pf.set ("Maplejaw");
Personfactory Pf=person::setname; equivalent to the following
Person Person=new person ("Maplejaw");
Personfactory pf=new personfactory{public
void Set (String name) {return
person.setname (name);
}
4, the JAVA8 API built-in function-type interface
Remember the supplier functional interface mentioned earlier, which is one of the functional interfaces built into the API, and some common built-in functional interfaces are described below. Supplier
Supplier provider, does not accept parameters, has return value
Supplier<person> supplier=new supplier<person> () {@Override public person get
() {return
new Person ();
}
;
Supplier<person> sp=person::new;
Function a parameter, a return value. Often used for data processing.
Function<string, integer> function=new function<string, integer> () {
@Override public
Integer Apply (String s) {return
integer.parseint (s);
}
};
Function<string, integer> Function=integer::p arseint;
Consumer consumer, with only one parameter, no return value
Consumer<string> consumer=new consumer<string> () {
@Override public
void Accept (String t) {
}
};
Comparator Comparison class
Comparator<integer> comparator=new comparator<integer> () {
@Override public
int compare (Integer O1, Integer O2) {
//TODO auto-generated method stub return
o1-o2;
}
;
predicate
predicate interface, the abstract method has only one parameter, which returns a Boolean type. The interface contains a variety of default methods to synthesize predicate groups into other complex logic (e.g., with, or, non):
Predicate<string> predicate=new predicate<string> () {
@Override public
boolean test (String t) { return
T.startswith ("H");
}
;
Boolean b=predicate.test ("hahaha");/to determine whether the condition is met
predicate<string> predicate = string::isempty;
Boolean b=predicate.test ("hahaha");/to determine whether the condition is met
Unaryoperator receives a parameter, returns a parameter with the same parameter type
Unaryoperator<string> unaryoperator=new unaryoperator<string> () {
@Override public
String apply (String s) {
//TODO auto-generated method stub return
s;
}
};
Binaryoperator receives two parameters, returns a parameter with the same parameter type
Binaryoperator<string> binaryoperator=new binaryoperator<string> () {
@Override public
String Apply (String T, String u) {
//TODO auto-generated method stub return
t+u;
}
;
5, three API Optional
Optional This is an introduction to prevent nullpointerexception anomalies. Optional provides a number of useful methods so that we do not have to explicitly test for null values.
optional<string> Optional = Optional.of ("Give you a Value");
Optional.ispresent (); Determine whether the null value
optional.get (); Gets the value if the null value throws an exception directly.
optional.orelse ("return null value"); Gets the value, if the null value returns the specified value.
Stream (Stream)
The newly added stream API (java.util.stream) introduces the real functional programming style into Java. This is the best complement to the Java class Library so far, because the stream API can provide a great deal of productivity for Java programmers, allowing programmers to write efficient, clean, and concise code.
Exposure to Rxjava may be familiar to the following code style, the creation of the Stream needs to specify a data source, such as java.util.Collection subclass, list or set, map does not support. The operation of the stream can be executed serially or in parallel.
How to use stream. Stream must have a data source. Then give it to a data source.
list<string> list = new arraylist<> ();
List.add ("Ddd2");
List.add ("Aaa2");
List.add ("BBB1");
List.add ("Aaa1");
List.add ("Aaa3");
List.add ("Bbb3");
List.add ("CCC");
List.add ("Bbb2");
List.add ("Ddd1");
foreach list New for loop method, foreach is a final action (only at the end)
Traverse Print Data
List.foreach (new consumer<string> () {
@Override public
void Accept (String t) {
SYSTEM.OUT.PRINTLN ("---->" +t);
}
);
Print the results as follows
---->DDD2
---->AAA2
---->BBB1
---->AAA1
---->AAA3
---->BBB3
---- >CCC
---->BBB2
---->DDD1
Filter filters
List.stream ()
. Filter (new predicate<string> () {
@Override public
boolean test (String t) {
Return T.startswith ("a");
}
)
. ForEach (New consumer<string> () {
@Override public
void Accept (String t) {
System.out.println ("- ---> "+t);
}";
Print the results as follows
---->AAA2
---->AAA1
---->AAA3
Sort Sort
List.stream (). Sorted ()//Sort and, if the comparator interface is not implemented, sort by default rules. Filter (New predicate<string> () {
@Override public boolean test (String t) {return T.startswith ("a"); The. ForEach (New consumer<string> () {@Override public void accept (String
T) {System.out.println ("---->" +t);
}
}); List.stream (). Sorted (new comparator<string> () {@Override public int compare (stri
Ng O1, String O2) {//TODO auto-generated Method stub return O1.compareto (O2); }). Filter (new predicate<string> () {@Override public boolean test (St
Ring t) {return T.startswith ("a"); The. ForEach (New consumer<string> () {@Override public void accept (String
T) { SYSTEM.OUT.PRINTLN ("---->" +t); }
});
Map
List.stream ()
. Sorted (new comparator<string> () {
@Override public
int Compare (string O1, String O2) {
//TODO auto-generated method stub return
O1.compareto (O2);
}
})
. Filter (new predicate<string> () {
@Override public
boolean test (String t) {return
t.startswith ("a ");
}
})
. Map (new function<string, string> () {
@Override public
String apply (String t) {
//TODO auto-generated method Stub return
t+ "---> Was handled by me";
}
)
. ForEach (New consumer<string> () {
@Override public
void Accept (String t) {
System.out.println ("- ---> "+t);
}";
---->AAA1---> was handled by me
---->AAA2---> was handled by me
---->AAA3---> I handled it.
Match matches, is a final operation
Boolean b= List.stream ()
. AnyMatch (New predicate<string> () {
@Override public
boolean test (String t {
//TODO auto-generated method stub return
t.startswith ("a");
}
);
SYSTEM.OUT.PRINTLN ("----->" +b);//true
boolean b= list.stream ()
. Allmatch (New predicate<string> () {
@Override public
boolean test (String t) {
//TODO auto-generated method stub
return T.startswith ("a");
}
);
SYSTEM.OUT.PRINTLN ("----->" +b);//false
Count Count, is a final action
Long Count = List.stream ()
. Filter (new predicate<string> () {
@Override public
boolean test (String t) {return
T.startswith ("a");
}
})
. Count ();
System.out.println (count); 3
Reduce specification, final operation
optional<string> Optional =
list
. Stream ().
sorted ()
. reduce (New binaryoperator< String> () {
@Override public
string apply (String T, String u) {return
t+u;
}
});
SYSTEM.OUT.PRINTLN ("---->" +optional.get ());
---->AAA1AAA2AAA3BBB1BBB2BBB3CCCDDD1DDD2
FindFirst Extract first, final operation
optional<string> Optional =
list
. Stream ().
sorted ()
. FindFirst ();
SYSTEM.OUT.PRINTLN ("---->" +optional.get ()); Aaa1
Parallelstream (Parallel stream)
There is not much difference between parallelization and previous code. And in parallel operation, the speed will be faster than the serial. However, it is necessary to note that the parallel stream does not have to be sorted in parallel streams.
List.parallelstream (). Filter (new predicate<string> () {@Over
Ride public boolean test (String t) {//TODO auto-generated method stub
Return T.startswith ("a"); The. ForEach (New consumer<string> () {@Override public voi D Accept (String t) {//TODO auto-generated Method Stub System.out.println ("---" ;"
+T);
}
});
List.parallelstream (). Sorted (). ForEach (New consumer<string> () {@Override
public void Accept (String t) {//TODO auto-generated method stub
SYSTEM.OUT.PRINTLN ("--->" +t);
}
}); Printed out and did not sort the