JAVA8 new features list __java

Source: Internet
Author: User
Tags local time
In fact, in terms of many linguistic features,. NET has been involved very early, here I simply list the JAVA8 part of the improvement implementation. All new feature improvements can be referenced here: http://www.iteye.com/news/28870-java-8-release
The largest of this improvement is the improvement of lambda expressions; second, the new Nashorn engine allows Java programs to interoperate with JavaScript code, as well as new date-time APIs, GC, concurrency, and much more.
This summary is mainly from:
New features and improved overview of JAVA8 http://www.oschina.net/translate/everything-about-java-8
JAVA8 ten new features detailed http://www.jb51.net/article/48304.htm
Series Article http://developer.51cto.com/art/201404/435591.htm

About JAVA8 IDE Compilation:
While some friends make eclipse support JAVA8 by installing plug-ins, individuals recommend updating your Eclipse firmware version to be thorough,
You need at least eclipse Kepler, I'm using the Mars version. Of course, if you originally used the Google ADT bundle that is not possible, even if you install Plug-ins by the way.

The following are some of the main features outlined:
1, the interface can have the default method, static method
Interface Formula {
    double calculate (int a);

    Default double sqrt (int a) {return
        math.sqrt (a);
    }
    public static void Test () {    }
}
Benefits: While multiple inheritance is supported, it is possible to provide a common implementation of abstractions for subclasses, which can be invoked directly by a subclass.
2. Function-Type interface
An interface defined by the @functionalinterface annotation that contains only an abstract method, so that its lambda expression is matched to the abstract method, and of course the default method can be added to the interface.
Example:
@FunctionalInterface
Interface Converter<f, t> {
    T convert (F from);
}
converter<string, integer> Converter = (from)-> integer.valueof (from);
Integer converted = Converter.convert ("123");

Comparator<string> C = (A, b)-> Integer.compare (A.length (), b.length ());
Runnable r = ()-> {System.out.println ("running!");}
3. Lambda
Each lambda expression corresponds to a type, typically an interface type, as an example:
list<string> names = Arrays.aslist ("Peter", "Anna", "Mike", "Xenia");
Collections.sort (names, (string A, string b)-> {return
    b.compareto (a);
});
Collections.sort (names, (string A, string b)-> B.compareto (a));
Collections.sort (names, (A, B)-> B.compareto (a));
Other examples:
(int x, int y)-> {return x + y;}
(x, y)-> x + y
x-> x * x
()-> x
x-> {System.out.println (x);}
4, method and constructor reference
The object of the scope must be an interface defined by @functionalinterface, and then pass:: Reference: Static method, Object method, constructor, and so on.
converter<string, integer> Converter = integer::valueof;
Integer converted = Converter.convert ("123");

converter<string, integer> Converter = Myconverter::convert;
String converted = Converter.convert ("Java");

Interface Personfactory<p extends person> {
    P Create (String firstName, String lastName);
personfactory<person> personfactory = person::new;
Person person = personfactory.create ("Peter", "Parker");
Example:
String::valueof//static method references x-> string.valueof (x)
Object::tostring/Non-static method references x-> x.tostring ()
X::tostring//Inherited function Reference ()-> x.tostring ()
Arraylist::new//constructor reference ()-> new arraylist<> (), pointing to either of its 3 constructor methods, determines which method is used based on the functional interface used.
5. Lambda Scopes
Similarly, you can access the outer local variables, instance fields, and static variables that are marked final.
If you access a non-static variable or object, the equivalent of each instantiation, the performance naturally does not access static good.
6. Method Local Variables
final int num = 1;//Here final can be omitted, but this cannot be modified by other external code after the expression scope is used.
int num = 1;
Converter<integer, string> stringconverter =
        (from)-> string.valueof (from + num);
num = 3;//error,

int count = 0 cannot be modified;
List<string> strings = Arrays.aslist ("A", "B", "C");
Strings.foreach (s-> {
    count++;//error, cannot modify this value});
7, anonymous read-write object fields, static variables
Unlike local variables, the fields of the instance and the static variables within the lambda are readable and writable.
Class Lambda4 {
    static int outerstaticnum;
    int outernum;
    void Testscopes () {
        Converter<integer, string> stringConverter1 = (from)-> {
            outernum =;
            Return string.valueof (from);

        Converter<integer, string> stringConverter2 = (from)-> {
            outerstaticnum =;
            Return string.valueof (from);}
        ;
    }
8. Lambda Control process
Final String secret = "Foo"; Boolean Containssecret (iterable<string> values) {
    Values.foreach (s-> {if (Secret.equals (s)) {
            ???// Want to end the loop and return true, but can ' t}
    }
9, the default method of accessing the interface
Unlike 1th, we cannot access the default method of an interface in a lambda expression.
Xformula Formula = (a)-> sqrt (A * 100);

JAVA8 contains a number of built-in functional interfaces that add @functionalinterface annotations so that they can be used on a lambda, such as a comparator or runnable interface.
At the same time, JAVA8 also extends some new functional interfaces that can be easily extended to the lambda, mainly:
Filter
Map
Flatmap
Peek
Distinct
Sorted
Limit
Substream
Foreach
ToArray
Reduce
Collect
Min
Max
Count
AnyMatch
Allmatch
Nonematch
FindFirst
Findany
Only a few of them are listed below:
(1) predicate
There is only one argument, which returns the Boolean type
predicate<string> predicate = (s)-> s.length () > 0;
Predicate.test ("foo");              True
predicate.negate (). Test ("foo");     False
predicate<string> isempty = string::isempty;
(2) Function
has a parameter and returns a result with the default method that can be combined with other functions
function<string, integer> tointeger = integer::valueof;
function<string, string> backtostring = Tointeger.andthen (string::valueof);//combination
backtostring.apply ("123" );     "123"
(3) Supplier
Without parameters, returns a value of any
supplier<person> personsupplier = person::new;
Personsupplier.get ();   New person
(4) Consumer
Performs operations on a single parameter
consumer<person> greeter = (p)-> System.out.println ("Hello," + p.firstname);
Greeter.accept (New person ("Luke", "Skywalker"));
(5) Comparator
Comparator<person> Comparator = (P1, p2)-> p1.firstName.compareTo (p2.firstname);
person P1 = new Person ("John", "Doe");
person P2 = new Person ("Alice", "Wonderland");
Comparator.compare (P1, p2);             > 0
comparator.reversed (). Compare (P1, p2);  < 0
(6) Optional
Non-functional interface, for a simple container whose value may be null or not recommended for object return in Null,java8, do not worry about null pointer exceptions.
optional<string> Optional = Optional.of ("Bam");
Optional.ispresent ();           True
optional.get ();                 "Bam"
optional.orelse ("fallback");    "Bam"
optional.ifpresent ((s)-> System.out.println (S.charat (0));     "B"
(7) Stream
Stream operation needs to specify a data source, such as: Collection, List, Set,map not supported.
The stream operation can be executed serially or in parallel, and its operations can have either intermediate or final forms.
Middle: Returns the stream itself
Final: Returns the result of the calculation
Data source list<string> StringCollection = new arraylist<> ();
Stringcollection.add ("Ddd2");
Stringcollection.add ("Aaa2"); Sort + Filter Stringcollection.stream (). Sorted (). Filter ((s)-> S.startswith ("a"). ForEach (System.out::p rintln)
; Map mapping, which converts an object to another type through a map, and the stream type returned by the map determines the Stringcollection.stream (). Map (string::touppercase) by the function return value that is passed into the map. Sor
Ted ((A, B)-> B.compareto (a)). ForEach (System.out::p rintln);
        Match Boolean Anystartswitha = Stringcollection.stream (). AnyMatch ((s)-> S.startswith ("a"));
        Allmatch ((s)-> S.startswith ("a"));
Nonematch ((s)-> s.startswith ("z"));
Count Long STARTSWITHB = Stringcollection.stream (). Filter ((s)-> s.startswith ("B"). Count ();
Reduce statute optional<string> reduced = Stringcollection.stream (). Reduce ((S1, S2)-> s1 + "#" + S2); Reduced.ifpresent (System.out::p rintln);
"AAA1#AAA2#BBB1#BBB2#BBB3#CCC#DDD1#DDD2"//serial, parallel Operation Values.stream (). Sorted (). Count (); ValueS.parallelstream (). Sorted (). Count ();//same result, but shorter time 
(8) Map
Map.putifabsent (i, "Val" + i);//No additional checks are required
Map.foreach ((ID, Val)-> System.out.println (Val));
Map.computeifpresent (3, (Num, Val)-> val + num);
Map.computeifpresent (9, (Num, val)-> null);
Map.computeifabsent (num-> "val" + num);
Map.getordefault ("not Found");  Not found
Map.merge (9, "VAL9", (value, NewValue)-> Value.concat (NewValue));
Map.get (9); Val9
10, Date API
(1) Clock
Clock are time zone sensitive and can be used to replace System.currenttimemillis ()
Clock Clock = Clock.systemdefaultzone ();
Long Millis = Clock.millis ();
Instant Instant = Clock.instant ();
Date legacydate = Date.from (instant); Legacy Java.util.Date
(2) Time zone ZoneID
Zoneid.getavailablezoneids ()
ZoneID zone1 = Zoneid.of ("Europe/berlin");
ZoneID zone2 = Zoneid.of ("Brazil/east");
System.out.println (Zone1.getrules ());
(3) LocalTime local time
LocalTime Now1 = Localtime.now (zone1);
LocalTime now2 = Localtime.now (zone2);
System.out.println (Now1.isbefore (Now2));  False
Long Hoursbetween = ChronoUnit.HOURS.between (Now1, now2);
Long Minutesbetween = ChronoUnit.MINUTES.between (Now1, now2);
LocalTime late = Localtime.of (in);
System.out.println (late);       23:59:59

datetimeformatter germanformatter =
    datetimeformatter
        . Oflocalizedtime ( Formatstyle.short)
        . Withlocale (Locale.german);
LocalTime leettime = Localtime.parse ("13:37", germanformatter);
System.out.println (leettime);   13:37
(4) Localdate
Localdate today = Localdate.now ();
Localdate tomorrow = Today.plus (1, chronounit.days);
Localdate yesterday = tomorrow.minusdays (2);
Localdate IndependenceDay = Localdate.of (2014, month.july, 4);
DayOfWeek DayOfWeek = Independenceday.getdayofweek ();
Localdate Xmas = localdate.parse ("24.12.2014", Germanformatter);
(5) LocalDateTime
LocalDateTime Sylvester = Localdatetime.of (2014, Month.december, N,);
DayOfWeek DayOfWeek = Sylvester.getdayofweek ();
Month Month = Sylvester.getmonth ();
Long Minuteofday = Sylvester.getlong (chronofield.minute_of_day);
LocalDateTime parsed = Localdatetime.parse ("Nov, 2014-07:13", formatter);
11, annotation annotation
Multiple annotations are supported and two new Target: @Target ({elementtype.type_parameter, elementtype.type_use}) are added
Defined:
@interface hints {
    hint[] value ();
}
@Repeatable (hints.class)
@interface Hint {
    String value ();
}
Use the old method
@Hints ({@Hint ("Hint1"), @Hint ("Hint2")})
class Person {}
//New method
@Hint ("Hint1")
@Hint ("Hint2")
Class Person {}
//Reflection
Hint Hint = Person.class.getAnnotation (hint.class);
SYSTEM.OUT.PRINTLN (hint);                   Null
hints Hints1 = Person.class.getAnnotation (hints.class);
System.out.println (Hints1.value (). length);  2
hint[] hints2 = Person.class.getAnnotationsByType (hint.class);
System.out.println (hints2.length);          2
12. Other
(1) An abstract class cannot be instantiated by using a lambda
Will increase the difficulty of reading the lambda, which will result in the execution of hidden code.
The factory approach can be used to resolve:
Ordering<string> order = (A, b)-> ...;
Ordering<string> order = Ordering.from ((A, b)-> ...);

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.