Article From:https://www.cnblogs.com/liangjiejava/p/9969126.html

Java BuilderPattern

package com.cathay;

/**
* @Description
* @TODO
* @Author liangjie@cathay-ins.com.cn
* @Date Creation time: 2018/11/16
**/
public class Person {

private String name;
private int age;
private boolean sex;

public String getName() {
return name;
}

public int getAge() {
return age;
}

public boolean isSex() {
return sex;
}

public static class Builder {
private String name;
private int age;
private boolean sex;

public Builder name(String n) {
name = n;
return this;
}

public Builder age(int a) {
age = a;
return this;
}

public Builder sex(boolean s) {
sex = s;
return this;
}

public Person build() {
return new Person(this);
}
}

private Person(Builder builder) {
name = builder.name;
age = builder.age;
sex = builder.sex;
}

}

LambdaExpression

Example

1.Replacing anonymous inner classes

Undoubtedly, lambda expressions are mostly used to replace anonymous inner classes, and the implementation of Runnable interfaces is a classic example of anonymous inner classes. Lambda expressions are powerful enough to replace the entire anonymous inner class with () – & gt! See the code:

If an anonymous inner class is used:

@Test
public void oldRunable() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“The old runable now is using!”);
}
}).start();
}
1
2
3
4
5
6
7
8
9
If lambda expression is used:

@Test
public void runable() {
new Thread(() -> System.out.println(“It’s a lambda function!”)).start();
}
1
2
3
4
The final output:

The old runable now is using!
It’s a lambda function!
1
2
Is it too powerful to be terrible? Is it too simple to be terrible? Is it clear that the focus is terrible? That’s the terrible thing about lambda expressions, which do what the previous class did with very little code! uuuuuuuuuuu

2.Iterating sets using lambda expressions

JavaCollection classes are often used in daily development, or even in no Java code. Iterative traversal is the most common operation for collection classes. 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);
}
1
2
3
4
5
6
7
8
9
10
11
If you are familiar with scala, you must be familiar with forEach. It can iterate over all objects in the set and bring lambda expressions into it.

languages.forEach(System.out::println);
1
This line looks a little like the scope parsing in c++, which is also possible here.

3.Implementing map with lambda expression

When we mention functional programming and lambda expressions, how can we not mention map… Yes, Java 8 certainly supports it. See 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));
}
1
2
3
4
5
The final output is:

10.5
21.0
31.5
1
2
3
mapFunctions can be said to be the most important method in functional programming. The function of map is to transform one object into another. In our example, cost is increased by 0,05 times by map method and then output.

4.Implementing map and reduce with lambda expression

Now that you mention map, how can you not mention reduce? Reduction, like map, is one of the most important methods in functional programming. The function of map is to change one object into another, while reduce implements merging 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);
}
1
2
3
4
5
6
The final results are as follows:

63.0
1
If we use the for loop to do this:

@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);
}
1
2
3
4
5
6
7
8
9
10
It is believed that the map + reduce + lambda expression is written more than one level higher.

5.filteroperation

filterIt is also an operation we often use. When manipulating collections, it is often necessary to filter out some 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));

}
1
2
3
4
5
6
7
The final results are as follows:

30.0
40.0
1
2
Does it feel like writing out Python or Scala in java? Is it so handsome?

6.Cooperate with Predicate, a functional interface

In addition to supporting functional programming style at the language level, Java 8 also adds a package called java. util. function. It contains many classes to support functional programming in Java. One of them is Predicate, which uses java.Utl. function. Predicate functional interfaces and lambda expressions can add logic to API methods and support more dynamic behavior with less code. The Predicate interface is well suited for filtering.

public static void filterTest(List<String> languages, Predicate<String> condition) {
languages.stream().filter(x -> condition.test(x)).forEach(x -> System.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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
The final output is:

Language starts 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
As you can see, Stream API’s filtering method also accepts a Predicate, which means that we can replace our custom filter () method with inline code written in it, which is also the magic of lambda expressions!
———————
Author: bitcarmanlee
Source: CSDN
Original: https://blog.csdn.net/bitcarmanlee/article/details/70195403
Copyright Statement: This article is the original article of the blogger. Please attach a link to the blog article for reprinting.

Java8 lambda10 examples of expressions

Example 1. Implementing Runnable with lambda expression

When I started using Java 8, the first thing I did was replace anonymous classes with lambda expressions, and implementing the Runnable interface was the best example of anonymous classes. Take a look at the runnable implementation before Java 8, which requires four lines of code and uses lambdaAn expression requires only one line of code. What have we done here? That is to replace the entire anonymous class with (->{} code blocks.

Copy Code uuuuuuuuuuuu
// Java 8Before:New Thread (new Runnable () {@OverridePublic void run () {System. out. println ("Before"Java 8, too much code for too little to do ";}}.Start ();//Java 8:New Thread (() - & gt; SyStem. out. println ("In Java 8, Lambda expression rocks!"). start ();
Copy Code uuuuuuuuuuuu

Output:

too much code, for too little to do
Lambda expression rocks !!

This example shows us the syntax of Java 8 lambda expressions. You can use lambda to write the following code:

(params) -> expression
(params) -> statement
(params) -> { statements }

For example, if your method doesn’t modify or rewrite the parameters, but just prints something on the console, you can write as follows:

() -> System.out.println("Hello Lambda Expressions");

If your method receives two parameters, it can be written as follows:

(int even, int odd) -> even + odd

Incidentally, the names of variables inside lambda expressions are usually shorter. This will make the code shorter and put it on the same line. So, in the above code, it is better to choose variable names a, B or x, y than even and odd.

Example 2. Event handling using Java 8 lambda expressions

If you have used Swing API programming, you will remember how to write event monitoring code. This is another classic use case for an old version of a simple anonymous class, but it can’t be done now. You can use lambda expressions to write better event listening code, as follows:

Copy Code uuuuuuuuuuuu
// Java 8Before:JButton show = new JButton ("Show");Show. addActionListener (new ActionListener () {@OverridePublic void action Performed (Action Event) {System. out. println ("Event handling without lam"BDA expression is boring ";}};// Java 8:Show. addActionListener ((e) - & gt; {System.ouT. println ("Light, Camera, Action!!!!!!!Lambda expressions Rocks");};
Copy Code uuuuuuuuuuuu

JavaAnother area where developers often use anonymous classes is to customize Comparators for Collections. sort (). In Java 8, you can replace ugly anonymous classes with more readable lambda expressions. It shouldn’t be difficult for me to keep this for practice.You can follow my routine in implementing Runnable and ActionListener using lambda expressions.

Example 3. Iterating lists using lambda expressions

If you have Java for a few years, you know that for collection classes, the most common operation is to iterate and apply business logic to various elements, such as processing lists of orders, transactions, and events. Because Java is a command language, all the loop code before Java 8 is sequential, that isIts elements can be processed in parallel. If you want to do parallel filtering, you need to write your own code, which is not so easy. By introducing lambda expressions and default methods, the question of what to do and how to do is separated, which means that Java collections now know how to iterate and canAt the API level, set elements are processed in parallel. In the following example, I’ll show you how to iterate lists using lambda or without lambda expressions. You can see that the list now has a forEach () method that iterates over all objects, andApply your lambda code to it.

Copy Code uuuuuuuuuuuu
// Java 8Before:List features = Arrays.asList ("Lambdas", "Default Method", "Stream API", "Date and Time API");FOr (String feature: features) {System. out. println (feature);}// After Java 8:List features = ArRays.asList ("Lambdas", "Default Method", "Stream API", "Date and Time API");Features. forEach (n->)System.out.println(n);// It is more convenient to use Java 8 method references, which are marked by: double colon operators./ / Scope parsing operators that look like C++.Features. forEacH (System.out:: println);
Copy Code uuuuuuuuuuuu

Output:

Lambdas
Default Method
Stream API
Date and Time API

The last example of the list loop shows how to use method reference in Java 8. You can see that the double colon and range resolution operators in C++ are now used in Java 8 to represent method references.

Example 4. Using lambda expression and functional interface Predicate

In addition to supporting functional programming style at the language level, Java 8 also adds a package called java. util. function. It contains many classes to support functional programming in Java. One of them is Predicate, which uses java.Utl. function. Predicate functional interfaces and lambda expressions can add logic to API methods and support more dynamic behavior with less code. Following is an example of Java 8 Predicate, which shows the filter setA variety of common methods for data integration. The Predicate interface is well suited for filtering.

Copy Code uuuuuuuuuuuu
public static void main(args[]){
    List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
 
    System.out.println("Languages which starts with J :");
    filter(languages, (str)->str.startsWith("J"));
 
    System.out.println("Languages which ends with a ");
    filter(languages, (str)->str.endsWith("a"));
 
    System.out.println("Print all languages :");
    filter(languages, (str)->true);
 
    System.out.println("Print no language : ");
    filter(languages, (str)->false);
 
    System.out.println("Print language whose length greater than 4:");
    filter(languages, (str)->str.length() > 4);
}
 
public static void filter(List names, Predicate condition) {
    for(String name: names)  {
        if(condition.test(name)) {
            System.out.println(name + " ");
        }
    }
}
Copy Code uuuuuuuuuuuu

Output:

Copy Code uuuuuuuuuuuu
Languages which starts with J :
Java
Languages which ends with a
Java
Scala
Print all languages :
Java
Scala
C++
Haskell
Lisp
Print no language :
Print language whose length greater than 4:
Scala
Haskell
Copy Code uuuuuuuuuuuu
// Better wayPublic static void filter (List names, Predicate condition) {Names. stream (). filter ((name)- & gt; (condition. test (name). forEach ((name) - & gt; {System. out. println (name + "";};}

As you can see, the Stream API’s filtering method also accepts a Predicate, which means that we can replace our custom filter () method with inline code written in it, which is the magic of lambda expressions. In addition, PredicateInterfaces also allow multiple conditional tests, as will be discussed in the next example.

Example 5. How to add Predicate to lambda expression

As mentioned in the previous example, java. util. function. Predicate allows two or more redicates to be synthesized into one. It provides methods similar to logical operators AND and OR, called and (), or (), and xor.(), which is used to merge the conditions passed into the filter () method. For example, to get all four-letter languages starting with J, you can define two separate Predicate examples to represent each condition, and then use Predicate.an.The D () method combines them as follows:

Copy Code uuuuuuuuuuuu
// You can even combine Predicate with and (), or () and XOR () logic functions.// For example, to find all names starting with J and four letters in length, you can merge two Predicates and pass inPredicate & lt; St.Ring & gt; startsWithJ = (n) - & gt; n. startsWith ("J");Predicate< String> fourLetterLong = (n) - & GT; n. length () == 4;Names. stream ()Filter (start with J. and (fourLetter Long)ForEach ((n) -&g)T; System.out.print ("nName, which starts with'J'and four letters long is:" +n)));
Copy Code uuuuuuuuuuuu

Similarly, or () and XOR () methods can also be used. This example highlights the following points: Predicate can be used as a separate condition as needed and then combined. In short, you can use Predica in traditional Java commandsTe interface can also make full use of lambda expression to achieve twice the result with half the effort.

Examples of Map and Reduce using lambda expressions in Java 8

This example introduces the most well-known concept of functional programming, map. It allows you to convert objects. For example, in this case, we convert each element of the costBeforeTax list into a post-tax value. We pass x-> x*x lambda expressionsTo the map () method, which applies it to every element in the stream. Then print out the list elements with forEach (). Using the collector class of streaming API, you can get all the tax-containing expenses. There are methods like toList () that map or anyThe results of other operations are combined. Since the collector does terminal operations on the stream, the stream cannot be reused afterwards. You can even synthesize all the numbers into one using the reduce () method of the stream API, as the next example will show.

Copy Code uuuuuuuuuuuu
// Add 12% tax to each order without lambda expressionList costBeforeTax = Arrays. asList (100, 200, 300, 400, 500);For (Integer c)Ost: costBeforeTax {Double price = cost + 12 * cost;System. out. println (price);}/ / use LAmbda expressionList costBeforeTax = Arrays. asList (100, 200, 300, 400, 500);CostBeforeTax. stream (). map ((co)St) - & gt; cost + 12 * cost. forEvery (System. out:: println);
Copy Code uuuuuuuuuuuu

Output:

Copy Code uuuuuuuuuuuu
112.0
224.0
336.0
448.0
560.0
112.0
224.0
336.0
448.0
560.0
Copy Code uuuuuuuuuuuu

Examples of Map and Reduce using lambda expressions in Java 8

In the previous example, you can see that map transforms collection class (such as list) elements. There is also a reduce () function that combines all values into one. Map and Reduce operations are the core operations of functional programming, because of their functions, reduce is also known asFor folding operation. In addition, reduce is not a new operation, you may already be using it. Cluster functions like sum (), AVG () or count () in SQL are actually reduce operations because they receive multiple values and return them.Return a value. The reduceh () function defined by the stream API can accept lambda expressions and merge all values. Classes like IntStream have built-in methods like average (), count (), sum () to do reThere are also mapToLong () and mapToDouble () methods for conversion. This does not limit you. You can use built-in methods or define them yourself. In this Java 8 Map Reduce example, let’s start with all the pricesThe lattice uses 12% VAT, and then calculates the sum by reducing ().

Copy Code uuuuuuuuuuuu
// Add a 12% tax on each order//Old method:List costBeforeTax = Arrays. asList (100, 200, 300, 400, 500);Double total = 0;For (Integer cost: costBeforeTax) {Double price = cost + 12 * cost;Tot = total + price;}System.out.println ("Total:" +total);//New methods:List costBeforeTax = Arrays. asList (100, 200, 300), 400, 500);Double bill = costBeforeTax. stream (). map ((cost) - & gt; cost + 12 * cost). reduce ((sum, cos)T) - & gt; sum + cost. get ();System.out.println ("Total:" +bill);
Copy Code uuuuuuuuuuuu

Output:

Total : 1680.0
Total : 1680.0

Example 7. Create a String List by Filtering

Filtering is a common operation for Java developers on large collections, and it’s amazingly simple to use lambda expressions and stream APIs to filter large collections of data. The stream provides a filter () method that accepts a Predicate object, which isA lambda expression is passed in as filtering logic. The following example filters Java collections with lambda expressions to help understand.

// Create a list of strings, each longer than 2List & lt; String & gt; filtered = strList. stream (). filter (x - & gt; X. length () & gt; 2)Collect (Collectors. toList ());System. out. printf ("Original List:% s, filtered list:% s% n"), strLisT, filtered;

Output:

Original List : [abc, , bcd, , defg, jk], filtered list : [abc, bcd, defg]

In addition, there is a common misunderstanding about the filter () method. In real life, when filtering, parts are usually discarded, but using filter () method is to get a new list, and each element conforms to the filtering principle.

Example 8. Applying functions to each element of a list

We usually need to use a function for each element of the list, such as multiplying by a number one by one, dividing by a number, or doing other operations. These operations are well suited to the map () method. You can put the transformation logic in the form of lambda expressions in the map () method, and you canThe elements of the collection are transformed, as shown below.

// Replace strings with capitals and link them with commasList< String> G7 = Arrays.asList ("USA", "Japan", "France", "Germany", "Italy")"U.K.", "Canada";String G7Countries = G7. stream (). map (x - & gt; X. toUpperCase (). collect (Collectors).Joining (",");System. out. println (G7Countries);

Output:

USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA

Example 9. Copy different values and create a sublist

This example shows how to use distinct () method of flow to de-duplicate a set.

// Create a square list with all the different numbersList & lt; Integer & gt; numbers = Arrays. asList (9, 10, 3, 4, 7, 3, 4);List< IntegerGt; distinct = numbers. stream (). map (i - & gt; I * i). distinct (). collect (Collectors. toList ());System.oUt. printf ("Original List:% s, Square Without duplicates:% s% n", numbers, distinct);

Output:

Original List : [9, 10, 3, 4, 7, 3, 4],  Square Without duplicates : [81, 100, 9, 16, 49]

Example 10. Calculate the maximum, minimum, total and average values of set elements

IntStream、LongStream In classes like DoubleStream, there is a very useful method called summaryStatistics (). You can return IntSummary Statistics, Long Summary StatisticS or DoubleSummary Statistic, which describes the various summary data of elements in the stream. In this case, we use this method to calculate the maximum and minimum values of the list. It also has getSum () and getAverage () methodsTo get the sum and average of all elements in the list.

Copy Code uuuuuuuuuuuu
//Get the number, minimum, maximum, sum, and average of numbersList & lt; Integer & gt; primes = Arrays. asList (2, 3, 5, 7, 11, 13, 17, 19, 23, 2)9);IntSummaryStatistics stats = primes. stream (). mapToInt ((x) - & gt; x). summaryStatistics ();System.oUt. println ("Highest prime number in List:" +stats. getMax ()));System. out. println ("Lowest prime num"BER in List: "+stats.getMin();"System.out.println ("Sum of all prime numbers:" +stats.getSum ());System.out.println ("Average of all prime numbers:" +stats.getAverage()));
Copy Code uuuuuuuuuuuu

Output:

Highest prime number in List : 29
Lowest prime number in List : 2
Sum of all prime numbers : 129
Average of all prime numbers : 12.9

LambdaExpression vs anonymous class

Since lambda expressions are about to formally replace anonymous inner classes in Java code, it is necessary to make a comparative analysis of them. A key difference is the keyword this. The this keyword of an anonymous class points to an anonymous class, while the thi of a lambda expressionThe s keyword points to the class that surrounds the lambda expression. Another difference is the way they are compiled. The Java compiler compiles lambda expressions into private methods of classes. Using Java 7 invokedynamic bytecode instructions to dynamically bind thisMethod.

Java 8 LambdaKey Points of Expressions

10A sample Java lambda expression, stream API

So far we have seen 10 lambda expressions in Java 8, which is a suitable amount of work for beginners. You may need to run the sample program in person to master them. Try to modify the requirements to create their own examples to achieve the purpose of rapid learning. I would also like to suggest that you use Net.Beans IDE to practice lambda expressions, it supports Java 8 well. Netbeans will prompt you when converting code into a functional form. Simply follow the instructions of Netbeans to easily convert anonymous classes into lambdaExpression. In addition, if you like to read, remember to look at the Lambdas of Java 8, the author of the book Practical Functional Programming (Java 8 Lambdas, pragmatic functional programming).It’s Richard Warburton, or you can look at Manning’s Java 8 in Action, which is not published yet, but I guess there’s a free PDF in Chapter 1 online. But before you get busy with something elseFirst, review the lambda expressions, default methods, and functional interfaces of Java 8.

1)lambdaExpressions can only be coded as follows: predefined functional interfaces using @Functional annotations, methods with an abstract function, or SAM (Single Abstract Method single abstract method) types. These are called lambdThe target type of an expression can be used as a return type or as a parameter to the lambda object code. For example, if a method receives a Runnable, Comparable, or Callable interface, it has a single abstract method that can be passed into a lambda expression。 Similarly, if a method accepts interfaces declared in the java. util. function package, such as Predicate, Function, Consumer, or Supplier, it can pass lambda expressions to it.。

2)lambdaMethod references can be used within an expression only if the method does not modify the parameters provided by the lambda expression. The lambda expression in this example can be replaced by a method reference, because it is only a simple method call with the same parameters.

list.forEach(n -> System.out.println(n)); 
list.forEach(System.out::println);  // Use Method Reference

However, if there are any modifications to the parameters, you can’t use method references. Instead, you need to type in a complete lambda expression, as follows:

list.forEach((String s) -> System.out.println("*" + s + "*"));

In fact, you can omit the type declaration of the lambda parameter here, and the compiler can infer from the class attributes of the list.

3)lambdaInternally, static, non-static and local variables can be used, which is called variable capture in lambda.

4)LambdaExpressions are also called closures or anonymous functions in Java, so don’t be surprised if colleagues call them closures.

5)LambdaMethods are translated into private methods within the compiler and invokedynamic bytecode instructions are dispatched for invocation. You can use the javap tool in JDK to decompile class files. Use javap-p or javap-c-The V command takes a look at the bytecode generated by the lambda expression. It should be roughly as follows:

private static java.lang.Object lambda$0(java.lang.String);

6)lambdaThe expression has a limitation that only final or final local variables can be referenced, which means that variables defined outside the domain cannot be modified within lambda.

List<Integer> primes = Arrays.asList(new Integer[]{2, 3,5,7});
int factor = 2;
primes.forEach(element -> { factor++; });
Compile time error : "local variables referenced from a lambda expression must be final or effectively final"

In addition, it is possible to access it without modification, as follows:

List<Integer> primes = Arrays.asList(new Integer[]{2, 3,5,7});
int factor = 2;
primes.forEach(element -> { System.out.println(factor*element); });

Output:

4
6
10
14

Therefore, it looks more like an immutable closure, similar to Python.




 










Leave a Reply

Your email address will not be published. Required fields are marked *