Introduction to Functional Programming -Lambda expression

As object-oriented Java programming language, if they are programmed according to the type of programming commands divided (Imperative Programming). Common logic programming paradigm as well as programming (Logic Programming), functional programming (Functional Programming).

As a function of programming a programming paradigm, in the scientific field, a data structure and computer programming elements embodiment, the calculation process as it is a mathematical function evaluation, and change the status to avoid the variable data.

What is functional programming? The simple answer: Everything is a mathematical function. Functional programming languages ​​can have objects, but these objects are usually constant - either function parameters, function return value to what is. There is no functional programming language for / next loop, because the logic means that there is a change of state. Alternatively the phase, this cycle logic functional programming language is recursive, the function as a parameter passing mode of implementation.

Lambda  expressions

Java 8 biggest change is the introduction of Lambda (Lambda is the Greek letter λ English name) expression - a compact way transfer behavior.

Lambda expressions of the form

The syntax of a lambda expression parameter list, arrow -> and a function of body composition. Body may be either a function expression, or may be a block of statements.

Expression: expression will be executed and then returns the results.

A block of statements: statement statement in the block will be executed in sequence, like a method statement.

The caller will return control to the statement of an anonymous method. break and continue can only be used in a loop.

If the body of the function has a return value, the function of each path inside the body must return value.

Function body for small lambda expressions, it eliminates the return keyword, making the syntax more concise. Here are some lambda expression:

(int x, int y) ‐> x + y () ‐> 42

(String s) ‐> { System.out.println(s); }

Receiving a first lambda expression X and y both shaping parameters and returns their sum; lambda expression does not receive the second parameter returns the integer '42'; a third lambda expression is a string and it printed to the console, it does not return a value.

Common applications

Alternative anonymous inner classes

There is no doubt, lambda expressions most used applications is an alternative anonymous inner class, implement Runnable is a classic example of an anonymous inner class. Function lambda expression is quite strong, with () -> you can replace the entire anonymous inner class! 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:

The old runable now is using!
 It's a lambda function!

Is not strong enough to terrible? It is not simply to terrible? It is not clear and focused to terrible? This is

Bogeyman lambda expressions, with minimal code completion before a class thing to do!

The collection using lambda expressions iterate

Java collection classes daily development is often used, even said no java code is not used to the collection class. . . The most common operation is to iterate collections traversed. See 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 scala students, certainly no stranger to forEach. It can iterate all the objects in the collection, and

lambda expression into it.

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

This line looks a bit like c ++ scope resolution inside wording here is also possible.

Realization map with lambda expressions

Mention of functional programming, a reference to lambda expressions, how can we not mention the map. Yes, java8 certainly support. See Code Example:

@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 final output:

10.5
21.0
31.5

map function can be said that the most important functional programming is a way to go. Action is to map an object is converted into another. In our example, the cost map method is through a 0.05-fold increase in size and output.

With a lambda expression to achieve map and reduce

As mentioned in the map, how can we not mention reduce. reduce the map as one of the most important and functional programming in a few ways. Action map is to become an object to another, and all values ​​reduce implementation sucked 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 do this thing with a for loop:

@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);
}

I believe the wording with map + reduce + lambda expression is higher than one level.

filter operation

We also operate a filter frequently. When a set of operations, often need to be filtered off from the original collection part of the element.

@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.0
40.0
Published 682 original articles · won praise 1391 · Views 1.71 million +

Guess you like

Origin blog.csdn.net/itcast_cn/article/details/104773758