1. Interfaces can add Non-abstract methods and static methods, with keyword default
The code is as follows:
Public interface Defaulable {
void Printname ();
default void Printage () {
System.out.println;
}
static void Printsex () {
System.out.println ("female");
}
Implemented as follows:
public class Defaulableimpl implements defaulable {
@Override public
void Printname () {
System.out.println ("Abel");
}
public static void Main (String [] args) {
defaulable d=new defaulableimpl ();
D.printname ();
D.printage ();
Defaulable.printsex ();
}
the differences between interfaces and abstract classes in Java1.8.
When all two interfaces define two identical default methods
default void Printage () {
Do something
},
The implementation class implements both interfaces at the same time, and there is a conflict. The implementation class needs to overwrite the default method () again. Abstract classes allow non-static and non final domains, allowing methods to become public,static and final all interface methods are essentially public.
JDK 8 controversially brings the advantages of abstract classes to the interface. The effect is that today there are a large number of abstract classes that may be replaced with interfaces by default methods. 2.:: Method Reference
A method reference provides a very useful syntax for directly referencing a method or constructor of an existing Java class or object (instance). Used in conjunction with lambda, method references make language construction more compact and less redundant code.
:: Is a use of the lambda after the introduction of the Java 8, which represents the reference,
For example, the static method of reference string::valueof;
such as the constructor reference, Arraylist::new
such as the output method of the reference
List.foreach (system.out::p rintln);
You can also reference the properties of a class.
Below, we use the class of car, which defines 4 methods, as an example, to differentiate between 4 different method references that are supported in Java.
public static class Car {public
static car Create (final supplier< car > Supplier) {return
supplier.get () ;
}
public static void Collide (final car car) {
System.out.println ("collided" + car.tostring ());
}
public void follow (final car another) {
System.out.println ("following the" + another.tostring ());
}
public void Repair () {
System.out.println ("repaired" + this.tostring ());
}
The first method reference is a constructor reference, and its syntax is class::new, or more generally class< T >::new. Note that the constructor has no parameters.
Final Car car = car.create (car::new); The new construct method that references car is
final list< car > cars = arrays.aslist (car);
The second method reference is a static method reference, and its syntax is Class::static_method. Note that this method accepts an argument of type car.
Cars.foreach (Car::collide);
The third method refers to a method reference for any object of a particular class, and its syntax is Class::method. Please note that this method has no parameters.
Cars.foreach (Car::repair);
Finally, the fourth method reference is a method reference for a particular object, and its syntax is Instance::method. Note that this method accepts a parameter of type car
Final Car police = car.create (car::new);
Cars.foreach (Police::follow);
Running the above Java program will have the following output on the console (the instance of the car may not be the same):
collided com.javacodegeeks.java8.method.references.methodreferences$car@7a81197d
Repaired com.javacodegeeks.java8.method.references.methodreferences$car@7a81197d
following the com.javacodegeeks.java8.method.references.methodreferences$car@7a81197d
3.Clock
The clock class provides a way to access the current date and time, clock is time zone sensitive and can be used instead of system.currenttimemillis () to get the current number of microseconds. A particular point in time can also be represented using the instant class, which can also be used to create old Java.util.Date objects.
ZoneID zone1 = Zoneid.of ("Europe/berlin");
System.out.println (Zoneid.getavailablezoneids ());
Clock Clock=clock.system (zone1); Clock Clock=clock.systemdefaultzone ()//Get the default time zone
Instant instant=clock.instant ();
Long Millis = Clock.millis ();
SYSTEM.OUT.PRINTLN (Millis)//Replaceable System.currenttimemillis ()
System.out.println (clock+ "-----SD" +instant);
If you need a date/time for a particular time zone, then Zoneddatetime is your choice. It holds the date and time that the ISO-8601 format has time zone information. Here are some examples of different time zones:
ZoneID zone1 = Zoneid.of ("Europe/berlin");
Clock Clock=clock.system (zone1);
Final Zoneddatetime zoneddatetime = Zoneddatetime.now ();
Final Zoneddatetime Zoneddatetimefromclock = Zoneddatetime.now (clock);
Final Zoneddatetime Zoneddatetimefromzone = Zoneddatetime.now (Zoneid.of ("America/los_angeles"));
System.out.println (zoneddatetime);
System.out.println (zoneddatetimefromclock);
System.out.println (Zoneddatetimefromzone);
Output results
2016-09-11t16:45:08.711+08:00[asia/shanghai]
2016-09-11t10:45:08.711+02:00[europe/berlin]
2016-09-11t01:45:08.724-07:00[america/los_angeles]
4. Base64
In Java 8, BASE64 encoding becomes the standard for Java class libraries. The Base64 class also provides a URL, mime-friendly encoder and decoder.
In addition to these ten new features, there are some other new features:
A better type-guessing mechanism: Java 8 has been greatly improved in terms of type speculation, which makes the code cleaner and does not require too many forced-type conversions.
Compiler optimization: Java 8 Adds the parameter name of the method to the byte code, so that the argument name can be obtained by reflection at run time only if the-parameters parameter is used at compile time.
Parallel (parallel) arrays: support for parallel processing of arrays, mainly the Parallelsort () method, which can greatly improve the speed of array sorting on multi-core machines.
Concurrency (concurrency): On the basis of new stream mechanism and lambda, some new methods are added to support aggregation operations.
Nashorn engine JJS: command line tools based on the Nashorn engine. It accepts some JavaScript source code as a parameter and executes the source code.
Class-Dependent parser jdeps: You can display the package-level or class-level dependencies of Java classes.
The JVM's PermGen space was removed: Metaspace (Jep 122) was substituted for it. 5.Optional
Optional is actually a container: it can hold the value of type T, or simply save null. Optional provides a number of useful methods so that we can use optional to detect null values.
person who = new person ();
person = null;
Boolean flag = optional.ofnullable (person). Ispresent ();
System.out.println ("Full Name is set?" + flag);
If the instance of the optional class is a non-null value, Ispresent () returns True and no returns FALSE. 5.LAMBDA Expressions (functional programming)
Functional programming can be said to be declarative programming. (There is an explanation at the end of the article.) Imperative programming: The Command "machine" How to do things, so whatever you want (what), it will be implemented according to your command. Declarative programming: Tell the Machine what you want (what) and let the machine figure out how to do it.
Lambda expressions allow you to use expressions instead of functional interfaces. A lambda expression, like a method, provides a normal list of arguments and a body that uses those arguments (the bodies, which can be an expression or a block of code).
Lambda expressions also enhance the collection library. Java SE 8 adds 2 packages for bulk operations on collection data: Java.util.function packages and Java.util.stream packages. Flow (stream) is like an iterator (iterator), but many additional features are attached. In general, lambda expressions and stream are the biggest changes since the Java language adds generics (generics) and annotations (annotation). LAMBDA expression simple syntax:
1. No parameters are required, the return value is 5
()-> 5
/2. Receives a parameter (numeric type), returns its twice times the value
x-> 2 * x
/3. Accept 2 parameters (numbers) and return their difference
(x, y) ; Computes
//4. Receive 2 int integers, return their and
(int x, int y)-> x + y
/5. Accepts a string object and prints on the console without returning any value (which looks like a return void)
(String s)-> System.out.print (s)
A For loop for a Lambda
Initialize data
list<string> str = new arraylist<> ();
for (int i = 0; i < i++) {
Str.add (i + "");
}
With an expression output, if you know it is a string, write a string, or you write a generic, and Java will automatically recognize it.
Str.foreach ((String)-> System.out.println (string+ ";"));
Str.foreach ((String)-> {
System.out.println (string+ ";");
System.out.println (string+ "additional operation");
Str.clear ();
Writing this makes the code simple.
An anonymous class can be substituted with a lambda expression. Similarly, you can use this when implementing the Runnable interface:
1.1 Use anonymous inner class
new Thread (new Runnable () {
@Override public
void Run () {
System.out.println ("Hello World! ");
Start ();
1.2 Use lambda expression
new Thread (()-> System.out.println ("Hello world!"). Start ();
2.1 Use anonymous inner class
Runnable Race1 = new Runnable () {
@Override public
void Run () {
System.out.println (" Hello world! ");
}
};
2.2 Use lambda expression
Runnable Race2 = ()-> System.out.println ("Hello world!");
Call the Run method directly (no new threads open!)
Race1.run ();
Race2.run ();
using Lambdas to sort collections
Way one, sorted by initials
list<string> str2 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Str2.sort ((E1, E2)-> E1.compareto (E2));
Str2.foreach ((String)->system.out.println (string+ ";"));
Str2.foreach ((E)-> System.out.println (e));
Sort by length
list<string> str3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Length from small to large sort
str3.sort ((E1, E2)-> e1.length ()-e2.length ());
Str3.foreach ((E)-> System.out.println (e));
You can also implement sorting using this method
List<string> STR3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Comparator<string> sortbyname= (String e1, string e2)-> e1.length ()-e2.length ();
Str3.sort (Sortbyname); Length from small to large sort
Str3.foreach ((e)-> System.out.println (e));
using lambdas and streams
Use Fileter filter to display
List<string> STR3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Output length greater than 3
str3.stream (). Filter ((String E1)-> (E1.length () > 3)). ForEach ((E)-> System.out.println (e));
The results are as follows
Abel
Bruce
Sean
Multiple filter combinations, or you can define filters in such a separate way
List<string> STR3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Define Filter
predicate<string> lengthfilter = (String E1)-> (E1.length () > 3);
Predicate<string> Confilter = (String E1)-> (E1.contains ("a"));
Str3.stream (). Filter (Lengthfilter). Filter (Confilter). ForEach ((E)-> System.out.println (e));
There is also the limit limit, the maximum minimum value method.
List<string> STR3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Sorted by first letter, output the first three
str3.stream (). Sorted (E1, E2)-> E1.compareto (E2)). Limit (3). ForEach ((E)-> System.out.println (e));
System.out.println ("------------------------------------------------------------");
Maximum output
String max=str3.stream (). Max ((e1,e2)-> (E1.length ()-e2.length ())). get ();
The shortest length
String min=str3.stream (). Min ((e1,e2)-> (E1.length ()-e2.length ())). get ();
System.out.println (max+ "---" +min);
Parallel computation of stream and the use of the Summarystatistics method to obtain various summary data of the elements in the stream
List<string> STR3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Parallel Computing
int sum=str3.stream (). Parallel (). Maptoint (P->p.length ()). sum ();
SYSTEM.OUT.PRINTLN (sum);
Use the Summarystatistics method to obtain various rollup data for elements in the stream
intsummarystatistics sumstatis=str3.stream (). Maptoint (p-> P.length ()). Summarystatistics ();
System.out.println ("Average Length" +sumstatis.getaverage () + "\ n the smallest length" +sumstatis.getmin () + "\ n the maximum length of" +sumstatis.getmax () + " \ n Seek sum "+sumstatis.getsum ());
In addition to lambdas the map method, you can also use the Collect method to place our result set in a string, a set or a treeset here does not explain the reference class's member variables and local variables
A lambda can refer to a class's member variables and local variables (if these variables are not final, they are implicitly converted to final, which is more efficient). For example, the following two code fragments are equivalent:
String separator = ",";
Arrays.aslist ("A", "B", "D"). ForEach (
(String e)-> System.out.print (e + separator));
And:
Final String separator = ",";
Arrays.aslist ("A", "B", "D"). ForEach (
(String e)-> System.out.print (e + separator));
5. I use Lambdas to cite some examples
Test class.
Package com.us;
Import java.util.*;
Import Java.util.function.Predicate;
Import java.util.stream.Collectors;
/** * Created by Yangyibo on 16/12/26. */public class Lambdatest {public static void main (string[] args) {//Foreacht ();//Threadt ();//
Sortt ();
Streamsfiltert ();
Streamscountt ();
Persontcomparator ();
Boysandgirls ();
Stringtointt ();
//lambda for loop private static void Foreacht () {list<string> str = new arraylist<> ();
for (int i = 0; i < i++) {Str.add (i + "");
} str.foreach ((String)-> System.out.println (string + ";"));
Str.foreach ((String)-> {System.out.print (string + ";");
System.out.println (String + "additional action");
});
Str.clear (); }//anonymous class thread operation private static void Threadt () {System.out.println ("current--" + thread.currentthread () . GetiD ()); Using lambda expression the thread new Thread (()-> System.out.println ("Hello World Thread!---" + Thread.currentthrea
D (). GetId ()). Start (); Using anonymous inner class there is no thread Runnable Race2 = ()-> System.out.println ("Hello World Runnable!--" + thread.currentthread (
). GetId ());
Race2.run (); //comparator sort private static void Sortt () {//mode one, sorted by first letter list<string> str2 = Array
S.aslist ("Abel", "Don", "Bruce", "Sean");
Str2.sort ((E1, E2)-> E1.compareto (E2));
Str2.foreach ((E)-> System.out.println (e));
System.out.println ("--------------Split Line--------------------");
Sort by length list<string> Str3 = arrays.aslist ("Abel", "Don", "Bruce", "Sean");
Length from small to large sort str3.sort ((E1, E2)-> e1.length ()-e2.length ());
Str3.foreach ((E)-> System.out.println (e));
System.out.println ("--------------Split Line--------------------"); Sort by length List<string> STR4 = arrays.aslist ("Abel", "Don", "BR