Java 8 is more than lambdas and streams

Source: Internet
Author: User

In the blink of an eye application upgrade JDK8 has been a few months, the Lambdas expression and Streams APIs did bring the students to the programming efficiency and code readability of the promotion, the code becomes more concise and direct, more in line with human thinking (it seems that the development of programming language is also the spirit of "people-oriented" thinking). ATA on the two new features of the article has been a lot of, immortal everyone eat almost, often home side dishes, the following summarizes some of the common Java 8 lambdas and streams outside the new features.

1. Default Method

Java single inheritance of the characteristics of a class can only have 1 parent class, if there is a common method implementation can only be written in the parent class, if the interface can not be implemented, but Java 8 in the Stream method encountered this problem. There is no, in the Collection interface to add a non- default stream method, must be in all implementations of the interface of the class to implement this method (did they really XXXList change it XXXSet ?) )

Ken (BU) (Yao) did not (LE), Oracle apes opened a back door (their things are convenient, they want to change), they used to default method solve the problem. Implemented in the Collection interface default method - stream , so that all other xxxlist are not changed, you can use this method directly. Of course, as long as the implementation class does not override this method, the instance invokes the implementation in the interface.

You can see that there are java.util.Collection indeed 3 default methods added.

default Spliterator<E> spliterator() {        return Spliterators.spliterator(this, 0);}default Stream<E> stream() { return StreamSupport.stream(spliterator(), false);}default Stream<E> parallelStream() { return StreamSupport.stream(spliterator(), true);}

Use is actually a default keyword, in interface the method of adding default will have 2 functions: A. The method must be implemented in the interface, and the method can not be implemented in subclasses.
In addition, the method can also be added in, with the use of the method of interface static default Direct static use of the interface default , reducing the write some additional util/helper classes.

Interface classPublicInterfaceBasejava {DefaultvoidSayhi() {System.out.println ("Hi default method"); }PublicvoidGoodbye (); //implementation class public  class childjava implements basejava{ @Override  public void goodbye () {System.out.println (" The method that must be implemented ");} public static void main (String...args) {ChildJava CJ = new Childjava (); Cj.sayhi (); //Default Method}}           
2. Optional

Business application objects tend to be larger, objects inside the object, objects inside the object ... In the process, always have to judge whether null it is, this invisible increase the depth of the process of the procedure (if not to judge, that is NullPointerException , the key is that once an anomaly, the troubleshooting is also time)

If it is this ordinary non-null judgment (in isPresent() lieu !=null ), in fact, as before, it seems that there is no easy (personal feeling even trouble, actually equivalent to the non-empty judgment encapsulated a Helper static method).

optional<String>str = optional.ofnullable ("Some returned value");It could be an empty System.out.printlnStr.ispresent ()?Str.get ():  "default value"); //Java 8system.out. println (str.orelse ( "default Value ")); //Java 8system.out. println (str!=null?str: "default value"); //java 7//see Java source code public boolean isPresent () {return value! =  null;} public t OrElse (t other) {return value! = null? Value:other;}                

However, in the case of complex objects, it becomes more efficient, especially with the combination stream (reduce max min) and lambdas expression usage. See the return value is Optional the case, will subconsciously to determine the non-empty, which compared with the previous, can reduce the program because of the nullpointerexception of the functional defects, improve the development efficiency (I remember a google three-party package has already had Optional this east).

3. String API

Scenario 1. Business applications handle most of the list and string, the common operation is to give you a list, handle the string into a string, or give you a string (separated by delimiter), processing to become a list (Wood method, Front end to string, back end to list, clip in the middle can only continue to foreach)

This is to be put before (Java 7), an ape would write:

1 A comma-delimited list of product ID strings for the front end list<String> itemidlist = ...;//from the IC to get the hot liststringbuffer sb = new stringbuffer (); //can also be used StringBuilder ... for (string itemid:itemidlist) {sb. append (itemId). append (//TODO BUG with one at the end,} return sb.tostring (); //2 front end of all the good separated Product ID list string, we turn to list to the back end string str =str.split (string> list = Arrays.aslist (arr);        

This is certainly not a problem, but in business logic processing, always come to this, an impact code beautiful (originally like a stiff tree, add a few of this, like a tree tumour, 100 lines of code 50 lines are for loop ...) ), the second is the idea of breaking the main business logic (instead of dealing with the contents of the For loop, beware of the last one).

With Java 8, things are going to be a lot better, and one or two lines of code are done:

1 A string that gives the front end a comma-delimited list of commodity IDslist<String> itemidlist =...;ReturnString.Join",", itemidlist);Of course, if you get an object, you need to work with streams to complete the join.list<itemdo> Itemdos = ... String names = Itemdos.stream (). map (Itemdo:: Getitemid). Collect (Collectors.joining (","));  Java 8 source String.Join implementation public static String join (charsequence delimiter, charsequence... elements) { Objects.requirenonnull (delimiter); Objects.requirenonnull (elements); //number of elements not likely worth arrays.stream overhead. Stringjoiner joiner = new Stringjoiner (delimiter); for (Charsequence cs:elements) {Joiner.add (CS);} return joiner.tostring ();}             
4. Date and Time API

Scenario 2. Business applications are always unavoidable and date time to deal with, and, after docking with multiple systems, to the date, time, date time, string, etc. back and forth Daoteng, front-end to string, database storage datetime , brother team of two party package incredibly as long as the date part of the string and so on, of course, the operation of the date, How many days ahead, how many days back

In Java 7, we use the longest in the calendar because it is simple and lightweight, and it supports date manipulation. In addition, in conjunction SimpleDateFormat , you can String convert any to date, then take advantage Calendar of the operation, and finally use another format that you SimpleDateFormat want to write to the front end. Typically, this is written like this:

 simpledateformat SDF =new SimpleDateFormat (  "YYYY/MM/DD")  "YYYY-MM-DD") ;D Ate date = Sdf.parse ( "2016/09/10") ; Calendar cal = calendar.getinstance (); Cal.settime (date) add (calendar.day_of_month, 10) ;D ate tendayslater = Cal.gettime ()       

Introduced in Java 8, LocalDate LocalTime representing the LocalDateTime date, time, date, and time, respectively, is straightforward, and provides thread-safe datetime operations in-place, generally more convenient than 7. The above code, in 8, can be written like this:

Localdate today = Localdate.now ();System.out.println ("Today is" + today); Localdate Specifiedday = Localdate.of (, Month.june,1);System.out.println ("Specific date is" + Specifiedday); Localdate fifthIn2016 = Localdate.ofyearday (2016,5);System.out.println ("5th Day" + fifthIn2016);Datetimeformatter.iso_local_datelocaldate Parsedday = localdate is used by default.Parse"2016-08-31");System.out.println ("Parsed Day is" + parsedday);Built-in yyyymmdddatetimeformatter basicisodate = datetimeformatter.basic_iso_date;Built-in yyyy-mm-dddatetimeformatter isolocaldate = datetimeformatter.iso_local_date;Custom Yyyy:MM:ddDateTimeFormatter customdate = Datetimeformatter.ofpattern ("Yyyy:MM:dd");//convert localdate formattedday = localdate. parse ( "20160821", basicisodate);  "Isolocaldate Day is" + Formattedday. Format (isolocaldate)); system.out.println ( "CustomDate Day is" + Formattedday.format (customdate)); //time operation localtime now = Localtime.now (); LocalTime later = Now.plus (5, HOURS); 30); Localdate afteronemonth = today.plusmonths (1); Localdate beforeonemonth = today.minusmonths (1);       

Localdate returns a completely new object each time (Localdate/localtime is final Class) relative to the calendar operation, which is more secure in a multithreaded environment.

5. Summary

Java 8 from the application upgrade to full use, there is probably a long way to go, after all, many of the existing code will not be updated to try new syntax and features. Experimenting with new syntax and features in new projects and code can lead to better experience and efficiency. In addition, functionally equivalent code, in addition to the grammatical differences, Java 7 and Java 8 in the performance of the difference, Java 8 really reduce the resources to improve efficiency? This problem has to be further explored in future use.

6. References

Joda-time
New features in Java 8
Java 8 Basic practices

Java 8 is more than lambdas and streams

Related Article

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.