Those years, the java8 we chased.

Source: Internet
Author: User

September Java9 will be released, in the last day of August decided to review the java8 those earth-shattering changes, deepen understanding and common progress.

We all know that Java differs from C++,c as an object-oriented language, with object-oriented thinking implementing most of Java's development until the advent of Java8,java8 introduces new ideas to Java (though this idea has long been in other languages)-functional programming, This is the collision of two ideas, causing just contact Java8 will feel that they are not writing Java code ... Okay, nonsense. Not much to say, first summarize some of Java8 's subversive change points:

1. Interfaces allow implementations:

 Public Interface MyInterface {    default  String getresult () {        return "Hello world!" ;    }}

This is called the default implementation, which is said to be introduced for foreach, the default method implementation brings another problem-multiple inheritance, but not the full meaning of multiple inheritance, because the inherited method, the equivalent of stateless multiple inheritance. So there must be some rules to deal with the problems of multiple inheritance:

    • Inherits the default method of the nearest interface.
    • Use the overridden method
    • When the above rules are still not confirmed, an error will be used.

2. Collection

Java8 The collection is the highlight of the deal. Let's take a look at a few common function-type interfaces:

Consumer

Supplier

Operator

Function

And some of the extensions on this basis

Biconsumer

Binrayoperator

Bifunction

interface does not introduce one by one, you can look at the source code, is also very simple, that is, the definition of the function of the process of abstracting a variety of different functions

The most commonly used tool class in the collection: Collectors is the protagonist of this analysis.

Before looking at the collectors class, you must first look at an interface: Collector

It has three types: the type of the entry, the middle type, the type of the argument, what is the interface for, and by the parameters it defines, we can basically guess that it defines a series of functions that pass the arguments through a series of processes, changes, and results in another. The source has a series of comments explaining the role of this class, here is a simple translation:

Collector is a class of 4 functions that are used to do the lazy evaluation equivalent of reduce. These 4 functions are:

Supplier<a> Supplier ();--used to generate a container for storing lazy evaluation results
Biconsumer<a, t> Accumulator ();--a function used to calculate the entry and put the result into a container
Binaryoperator<a> combiner ();--used to combine two containers into a single container. (This is an important step in a fork/join)
Function<a, r> Finisher ();--a function that transforms the results of the container into the desired result.
In fact, it has a 5th parameter that indicates whether collector is thread-safe or unsafe, or that A is r does not require the last step.

Collector introduced here, in collectors there is the default implementation of collector.

Collectors inside defines a lot of tools, but, in order to show the charm of functional programming, we pick a long point out to analyze a: Groupingby method, the source code is as follows:
 Public Static<t, K, D, A, MextendsMap<k, d>>Collector<t,?, m> Groupingby (function<?SuperT?extendsK>classifier, Supplier<M>mapfactory, Collector<?SuperT, A, d>downstream) {Supplier<A> Downstreamsupplier =Downstream.supplier (); Gets the container function of the downstream Biconsumer<a, huh?SuperT> Downstreamaccumulator =Downstream.accumulator (); Gets the calculation function for the downstream reduce operation Biconsumer<map<k, A>, t> accumulator = (m, T){//The function that puts the result of the calculation in the map (also the new Collector's calculation function) K key= Objects.requirenonnull (classifier.apply (t), "element cannot is mapped to a null key"); A Container= M.computeifabsent (key, K-downstreamsupplier.get ());                                    This step is the key, through the map key to determine whether it is the same class, if the same class, then return the original container, or use the downstream function to create a container downstreamaccumulator.accept (container, t);        Fill the container with values}; Binaryoperator<map<k, a>> merger = Collectors.<k, A, Map<k, a>>Mapmerger (Downstream.combiner ()); Gets the merge function @SuppressWarnings ("Unchecked") Supplier<map<k, a>> mangledfactory = (supplier<map<k, a>>) Mapfactory; The function returns the result container function (map type)if(Downstream.characteristics (). Contains (Collector.Characteristics.IDENTITY_FINISH)) {//If the type of downstream is the IDE Ntity_finish then return to the new collectorreturn NewCollectorimpl<>(Mangledfactory, accumulator, merger, CH_ID); }        Else{@SuppressWarnings ("Unchecked") Function<a, a> downstreamfinisher = (Function<a, a>) Downstream.finisher (); Otherwise, the function functions that get the result of the calculation<map<k, A>, m> finisher = Intermediate{//Generate new result function intermediate.replaceall (k, v)-downstreamfinisher.apply (v)); @SuppressWarnings ("Unchecked") M Castresult=(M) intermediate; returnCastresult;            }; return NewCollectorimpl<>(Mangledfactory, Accumulator, merger, finisher, Ch_noid); }    }

Let's look at an example in the note:

Map<department, integer> totalbydept          = employees.stream ()                   . Collect ( Collectors.groupingby (Employee::getdepartment,                                                    collectors.summingint (employee::getsalary)));

This example is to calculate the company each department staff salary synthesis, specific pojo will not give.

Throughout the process, Groupingby downstream (Collector) (literal translation: downstream flow) According to the rules of Classfier, and puts the results in a map container generated by the Mapfactory function, returning the new Collector. We see how an old collector through a series of processing, into a new collector, in fact, it is still not finished, we can still
The new collector do more, and none of this happens until we call a method of early evaluation, and the real action takes place, As stream.collect above, functional programming operations are no longer data, but functions, which can be considered as a function to decorate another function to form a new function.
In short, functional programming has not only thought, but also a programming habit, if we do not, do not write, even if more, is also on paper.
Java8 still need more practice and exploration.
JAVA9 greet you with your arrival.







Those years, the java8 we chased.

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.