Long Life Road, learn some Jakarta basic-JAVA8 functional programming

Source: Internet
Author: User
Tags instance method

interface Default Method

The default method of the interface is added after the Java8 version, not only the abstract method, but also the interface can contain several instance methods, define the instance method within the interface (but note that the default keyword is required)

The method defined here is not an abstract method, but an instance method with a specific logic.

  Example: Define interface animal, which contains the default method eat ().

/***/Publicinterface  Animal    {void call ()    ; default void eat () {        System.out.println ("Animal eat Default Method");}    }
View Code

Defines a dog class to implement the interface animal.

  

/** * Created by ZJC on 2018/4/9. */public class Dog implements  Animal {    @Override public    Void Call () {        System.out.println ("Wangwang");    }}

  

Test:

/** * Created by ZJC on 2018/4/9. */public class Animaltest {public    static void Main (string[] args) {        dog dog = new Dog ();        Dog.call ();        Dog.eat ();    }}

  Output Result:

  Advantage:

the 1.jdk8 default method allows the interface method to define the default implementation, and all subclasses will have the method and implementation, does not break existing code. Sometimes we need to extend a new method on the interface that has been put into use, before JDK8 we have to add the implementation of the method to all the implementation classes, otherwise the compilation will fail. If you change the implementation of a few classes and have permission to modify the workload may be relatively small, if the implementation of a lot of class changes or we do not have permission to modify the implementation of the source code of the class, it is more troublesome, by providing this default method solves this problem, he provides an implementation, The default implementation is used when no other implementations are shown, so that the newly added method does not break existing code.

2. The default method is optional: Subclasses can override the default implementation based on different requirements. If you define a default method in an interface, the subclass does not need to implement the default implementation, and if there is a special requirement or need, you can override the implementation.

  

/** * Created by ZJC on 2018/4/9. */public class Dog implements  Animal {    @Override public    Void Call () {        System.out.println ("Wangwang");    }    Subclasses can Override the default implementation according to different requirements    @Override public    void Eat () {        System.out.println ("No Default");}    }

  

Static methods

In the Java8 interface, we can write not only the default method, but also the static method.

  

1. Replace anonymous inner classes

There is no doubt that the most common use of lambda expressions is to replace anonymous inner classes, while implementing the Runnable interface is a classic example of an anonymous inner class. Lambda expressions are quite powerful and can replace the entire anonymous inner class with ()! Please look at the code:

If you use an anonymous inner class:

    @Test    public void oldRunable() {        new Thread(new Runnable() { @Override public void run() { System.out.println("The old runable now is using!"); } }).start(); }

And if you use a lambda expression:

    @Test    public void runable() {        new Thread(() -> System.out.println("It‘s a lambda function!")).start(); }

The final output:

is using!It‘s a lambda function!

Isn't it powerful to the horror? Isn't it simple to be scary? Is it clear that the focus is on the scary? That's the scary thing about lambda expressions, with very little code to do what the previous class did!

2. Iterating over a collection using a lambda expression

The Java Collection class is often used in everyday development, even if no Java code is used in the collection class ... The most common operation for a collection class is to iterate through it. Please look at the comparison:

    @Test    public void iterTest() {        List<String> languages = Arrays.asList("java","scala","python"); //before java8 for(String each:languages) { System.out.println(each); } //after java8 languages.forEach(x -> System.out.println(x)); languages.forEach(System.out::println); }

If you are familiar with Scala, you must not be unfamiliar with foreach. It iterates through all the objects in the collection and brings the lambda expression into it.

languages.forEach(System.out::println);

This line looks a bit like the syntax of the scope parsing in C + +, which is also possible here.

3. Implementing a map with a lambda expression

A reference to functional programming, a reference to lambda expression, how can not mention the map ... Yes, Java8 is certainly supportive. Take a look at the sample code:

    @Test    public void mapTest() {        List<Double> cost = Arrays.asList(10.0, 20.0,30.0); cost.stream().map(x -> x + x*0.05).forEach(x -> System.out.println(x)); }

The result of the final output:

10.521.031.5

The map function can be said to be one of the most important methods in functional programming. The role of map is to transform one object into another. In our example, the cost is increased by 0, 05 times times the size of the map method and then output.

4. Using lambda expressions to implement map and reduce

Since the reference to map, how can we not mention reduce. Reduce, like map, is one of the most important methods in functional programming ... The purpose of map is to change one object to another, and reduce to merge all values into one, see:

    @Test    public void mapReduceTest() {        List<Double> cost = Arrays.asList(10.0, 20.0,30.0); double allCost = cost.stream().map(x -> x+x*0.05).reduce((sum,x) -> sum + x).get(); System.out.println(allCost); }

The end result is:

63.0

If we use a For loop to do this thing:

    @Test    public void sumTest() {        List<Double> cost = Arrays.asList(10.0, 20.0,30.0); double sum = 0; for(double each:cost) { each += each * 0.05; sum += each; } System.out.println(sum); }

It is believed that the MAP+REDUCE+LAMBDA expression is more than a level.

5.filter operation

Filter is also an operation that we often use. When working with collections, it is often necessary to filter out a subset of elements from the original collection.

    @Test public void Filtertest () {list<double> cost = Arrays . Aslist (10.0, 20.0,30.0,40.0); list<double> filteredcost = Cost. Stream (). Filter (x, x > 25.0). Collect ( Collectors. ToList ()); Filteredcost. ForEach (x-System. Out. println (x) ) ; }

The final result:

30.040.0

Write Java out of Python or Scala feel there! is not handsome to explode!

6. Predicate with functional interface

In addition to supporting functional programming styles at the language level, Java 8 also adds a package called java.util.function. It contains a number of classes to support functional programming in Java. One of these is predicate, which uses the Java.util.function.Predicate function interface and lambda expressions to add logic to the API methods and to support more dynamic behavior with less code. The predicate interface is ideal for filtering.

public static void Filtertest (list<string> languages, predicate<string> condition) {languages. Stream (). Filter (Condition X. Test (x)). ForEach (System x. Out. println (X +" ")); } public static void Main (string[] args) {list<string> languages = Arrays. Aslist ("Java","Python","Scala","Shell","R"); System. Out. println ("Language starts with J:"); Filtertest (Languages,X-X. StartsWith ("J")); System. Out. println ("\nlanguage ends with a:"); Filtertest (Languages,X-X. EndsWith ("A")); System. Out. println ("\nall languages:"); Filtertest (languages,X-True); System.out. println ("\nno languages:"); Filtertest (languages,X, false); System.out. println ("\nlanguage length bigger three:"); Filtertest (languages, X-x . Length () > 4);}       

The result of the final output:

with J: Java Language ends with a: Java scala All languages: Java Python scala Shell R No languages: Language length bigger three: Python scala Shell 

  

Long Life Road, learn some Jakarta basic-JAVA8 functional programming

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.