JAVA 8 new features (worth learning)

Source: Internet
Author: User


JAVA 8 has been there for a long time, a large number of internet companies have been used, and even many well-known internet companies have stepped on a lot of pits, there are some Daniel share their actual combat experience. to many well-known internet companies are often asked by the interviewer, do you know Java 8? Do you know some of its new features? Seems to be a question that the interviewer must ask. this blog post, just a brief introduction of the new features, students also have their own practical operation, in-depth understanding, the best practical application to the project, if you are in the project group with the earlier, with more students, will be other colleagues notice you, haha.


Lambda expressions and functional interfaces

Here is the simple lambda representation of the application, the code is very concise, the direct item is a string in the list collection, the output will be

, item is the compiler automatically infers that it is a string type

list<string> list = arrays.aslist ("SDC", "ZS", "ls", "ww"), List.foreach (item, {SYSTEM.OUT.PRINTLN (item);}); Stream.of (12,21,13,31). Filter (S, {System.out.println ("out:" +s); return true;}). ForEach (System.out::p rintln);;


This is a simple lambda expression, lambda in fact, and the function of the interface is much more, Java8 also have a lot of classes are functional interfaces, what is a functional interface? function interface refers to the interface of only one function, is not very close to the mouth, what does it matter? I also do not know, the function interface is customizable, the general re-interface at the top plus @FunctionalInterface This annotation, is the function interface, the general function interface is not allowed to have other functions, but the default method and static method can be excluded, In the previous Java interface did not see can write method, Java8 can write the default method.


Here's a simple way to write a default method and abstract method.

Private interface Defaultinterface {default String Defaultmethod () {return ' default method ';}} Private interface Defaultinterfacestatic {static String Staticmethod () {return ' static method ';}}


Have the time of the classmate to see collection<e> This interface of things, this collection interface some use the default method of implementation, some is it itself, some are inherited iterable<t> This interface overrides the default method in this interface. For example:

Default Stream<e> Stream () {return Streamsupport.stream (Spliterator (), false); }


Students can do their own writing function interface, and the default method in the interface, try, whether their own projects can be modified to such.


repeating annotations:

Java 8 can also define duplicate annotations, Java itself is supported by self- defined annotations , such as the following

@Target ({elementtype.method, elementtype.type}) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Test {String test () default "none";}

This is a custom annotation.


Java8 define repeating annotations,

@Repeatable (Filters.class)

Add this on the note, you can define duplicate annotations, but the general company development or large-scale company development, custom annotations are more, but what is the use of repeated annotations, I still do not understand, so this piece is a brief introduction, how to define the line, repeating the annotation of what scene use I am not very clear.


Streams

This feature is probably a more advanced Java 8 feature, when writing with Java, the collection is often used the most, writing an interface is likely to involve the collection. Usually the iteration logic of the collection is a for loop, and streams hides the operation, simplifying development. Again java8 before the collection is loaded in memory, very occupy the inside, but have to use, streams is again access to the time only to start computing.

What is streams? Here are a few simple examples to explain

list<string> list = arrays.aslist ("SDC", "ZS", "ls", "ww"); This is a set of flow List.stream (). Filter (S-s.startswith ("s") ). Map (String::touppercase). Sorted (). ForEach (System.out::p rintln), or it can be arrays.aslist ("SDC", "ZS", "ls", "ww"). Stream (). FindFirst (). Ifpresent (System.out::p rintln);


The streams contains both intermediate and final forms of operation, the intermediate operation returns a streams, but there is no output, and the total operation is to return the result. The above-mentioned Map,sorted,findfirst are intermediate operations, and if you do not add the following, there will be no output operation, most of the streams operations can use lambda expressions.


Streams class has sequential streams and parallel streams, parallel to see is multithreaded class, suitable for use in multi-threading.

Arrays.aslist ("SDC", "ZS", "ls", "ww"). Stream (). FindFirst (). Ifpresent (System.out::p rintln);//stream.of ("SDC", " Zs "," ls "," ww "). FindFirst (). Ifpresent (System.out::p rintln);//intstream.range (1, 4). ForEach (System.out:: println);//arrays.stream (new int[]{4,5,6}). Map (n -> 2*n +1). Average (). Ifpresent ( System.out::p rintln),//intstream.range (1, 4). Maptoobj (p ->  "sucess"  + p). ForEach ( System.out::p rintln),//stream.of (100.0, 200.0, 300.0). Maptoint (Double::intvalue). MAPTOOBJ (h - > h+ "str"). ForEach (System.out::p rintln);//stream.of (12,21,13,31). Filter ( s -> { System.out.println ("Out:"  +s);  return true;}); /stream.of (12,21,13,31). Filter ( s -> {system.out.println ("Out:"  +s); return  true;}). ForEach (System.out::p rintln);; /stream.of ("DS", "QW", "Ty", "Op", "as")//.map (S -> {//system.out.println ("Map:"  + s);// Return s.touppercase ();//})//.filter (S -> {//system.out.println ("Filter:"  + s);//return s.startswith ("Q");//})//. foreach (S -> {//system.out.println ("foreach:"  + s);//});//stream.of ("DS", "QW", "Ty", "Op") , "as")//.filter (S -> {//system.out.println ("Filter:"  + s);//return s.startswith ("Q ");//})//.map (S -> {//system.out.println (" Map: " + s);//return s.touppercase ();/}) . foreach (S -> {//system.out.println ("foreach:"  + s);//});//stream.of ("DS", "QW", "Ty", " Op "," as ")//.sorted ((S1,&NBSP;S2)  -> {//system.out.println (" Sorted: " + s1 +", " &NBSP;+S2),//return s1.compareto (S2),//})//.filter (S -> {//system.out.println ("Filter:"  + s),//return s.startswith ("Q"),//})//.map (S -> {//system.out.println ("Map:"  + s),//return s.touppercase (),//})//.foreach (S -> {//system.out.println ("ForEach:  + s);//stream.Of ("DS", "QW", "Ty", "Op", "as")//.filter (S -> {//system.out.println ("Filter:"  + s);// Return s.startswith ("q");//})//.sorted ((S1,&NBSP;S2)  -> {//system.out.println ("Sorted:"  + s1 + ","  +s2),//return s1.compareto (S2);//})//.map (s -> {// SYSTEM.OUT.PRINTLN ("Map:"  + s);//return s.touppercase ();/})//.foreach (s -> {// System.out.println ("foreach:"  + s);//});//stream<string> stream = stream.of ("A1 ", " D3 ", " I9 "," R8 "). Filter ( s-> s.startswith (" I "));//stream.anymatch (s ->  true);//stream.nonematch (s -> true);//supplier<stream<string>> streamsupplier  =  ()  ->stream.of ("A1",  "D3",  "I9", "R8"). Filter ( s-> s.startswith ("I" );//streamsupplier.get (). AnyMatch (S -> true);//streamsupplier.get (). Nonematch (s ->  True) advanced features of;//stream  List<user> userlist = arrays.aslist (New user ("SDC",  20),  new user ("Zhangsan", &NBSP;20),  new user ("Lisi",  34));//list<user> newlist = userlist.stream (). Filter (U -> u.getuser (). StartsWith ("S")). Collect (Collectors.tolist ());//set<user> set  = userlist.stream (). Filter (U -> u.getuser (). StartsWith ("S")). Collect (Collectors.toset ( ));//system.out.println (set);//map<integer, list<user>> usergmap =  Userlist.stream (). Collect (Collectors.groupingby (U -> u.getage ()));//usergmap.foreach (age, p )  -> {//system.out.println (age +  "| | |" &NBSP;+&NBSP;P);//double averrage = userlist.stream (). Collect (Collectors.averagingint (U  -> u.getage ()));//system.out.println (averrage);//string phrase = userlist.stream ( ). Filter (U -> u.getage ()  >=19). Map (P -> p.getUser ()). Collect (Collectors.joining (" and ",  " in ",  " high age ") );//system.out.println (phrase);


These are some basic methods, I think the use of their own, actual combat, probably a lot of people are not too accustomed to these operations.





JAVA 8 new features (worth learning)

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.