Java8 lambda expression examples

  • 1.1 implements the Runnable with lambda expressions

Alternatively anonymous classes using a lambda expression, to achieve the best example of the anonymous Runnable interface class. Look runnable implementation before 8 Java, it takes 4 lines of code, and the use of lambda expressions only one line of code. We are here to do anything at all? That is by () -> {} replace the entire code block anonymous classes.

// Java 8之前:
new Thread(new Runnable() {
    @Override
    public void run() {
    System.out.println("Before Java8, too much code for too little to do");
    }
}).start();

//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();

This example shows us grammar Java 8 lambda expression. You can use a lambda write the following code:

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

For example, if your method does not modify the parameters, rewrite, just print something in the console, then you can write:

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

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

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

Incidentally, the name usually internal variable lambda expressions to get up short. It makes the code shorter and on the same line. Therefore, in the above code, the choice of the variable name a, b or x, y than even, odd better.

  • 1.2 Java 8 lambda expressions for event processing

If you used the Swing API programming, you'll remember how to write event listener code. This is another version of the old classic simple anonymous class of use cases, but now can not be the case. You can write better with a lambda expression event listener code as follows:

// Java 8之前:
JButton show =  new JButton("Show");
show.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("Event handling without lambda expression is boring");
    }
}); 

// Java 8方式:
show.addActionListener((e) -> {
    System.out.println("Light, Camera, Action !! Lambda expressions Rocks");
});

Java developers often use anonymous class is another place to Collections.sort () custom Comparator. In Java 8, you can use a more readable lambda expression to replace the ugly anonymous class.

  • 1.3 using a lambda expression to iterate over the list

If you make a few years Java, you know for the collections, the most common operation is iterative, and the business logic is applied to each element, such as a list of processing orders, transactions and events. Because Java is an imperative language, Java code for all cycles prior to 8 are sequential, i.e., parallel processing may be performed on its elements. If you want to filter in parallel, you need to write their own code, which is not so easy. By introducing lambda expressions and the default method, the problem of what to do and how to do it separately, which means that Java collections now know what to do iterative, and can be processed in parallel collection element in the API level. The following example, I will describe how to iterate over the list in the case of lambda or without the use of lambda expressions. You can see a list now have a forEach () method, which can iterate over all the objects, and you use the code in which the lambda.

// Java 8之前:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature : features) {
    System.out.println(feature);
} 

// Java 8之后:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));

// 使用Java 8的方法引用更方便,方法引用由::双冒号操作符标示,
// 看起来像C++的作用域解析运算符
features.forEach(System.out::println);
  • 1.4 lambda expression and functional interfaces Predicate

In addition to the language level support functional programming style, Java 8 has also added a package called java.util.function. It contains many classes for functional programming support of Java. Wherein a is the Predicate, using java.util.function.Predicate functional interface and lambda expressions, logic may be added to the API methods support more dynamic behavior with less code. The following are examples of Java 8 Predicate, showing a variety of commonly used method of filtering a collection of data. Predicate interface is very suitable for making filter.

public static void main(String[] args) {
    List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");

    System.out.println("Languages which starts with J :");
    filter(languages, (str)->((String)str).startsWith("J"));

    System.out.println("Languages which ends with a ");
    filter(languages, (str)->((String)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)->((String)str).length() > 4);
}

public static void filter(List<String> names, Predicate condition) {
    for(String  name: names)  {
        if(condition.test(name)) {
            System.out.println(name + " ");
        }
    }
}

Output:

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

// 更好的办法
public static void filter(List names, Predicate condition) {
    names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
        System.out.println(name + " ");
    });
}

You can see, Stream API filtration method also accepts a Predicate, which means that we can replace the custom filter () method as written on the inside of inline code, this is the magic of the lambda expression. Further, Predicate interfaces allow multiple testing conditions.

  • 1.5 How to join Predicate in lambda expressions.

Speaking of the example, java.util.function.Predicate allows two or more Predicate a synthesis. It provides similar logical operators AND and OR a method, called and (), or (), is used to filter incoming conditions of the process were pooled (). For example, to get all of J, length four-letter language, can define two separate Predicate example represent each condition, then Predicate.and () method of combining them as follows:

// 甚至可以用and()、or()逻辑函数来合并Predicate,
// 例如要找到所有以J开始,长度为四个字母的名字,你可以合并两个Predicate并传入
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
names.stream()
    .filter(startsWithJ.and(fourLetterLong))
    .forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n)); 

Similarly, it may be used or () method. This embodiment focuses on the following points: Predicate may need to be merged and then used as a single condition. In short, you can use the traditional way Predicate Java command interface also can take advantage of a lambda expression to achieve a multiplier effect.

  • 1.6 Java 8 in the Map and Reduce example using lambda expressions

This example describes the best known functional programming concept map. It allows you to convert objects. For example, in this embodiment, we convert each element of the list a value costBeforeTax after tax. We x -> x * x lambda expression passed map () method, which is to be applied to each element stream. Then forEach () will print out a list of elements. Flow collector using API classes can get all the tax overhead. There toList (), or a method to map the results of any other operations combined. Since the collector terminal operation done on the stream, and therefore can not be reused after they flow. You can even () method to reduce all digital synthesizer with a stream API, an example will be mentioned next.

// 不使用lambda表达式为每个订单加上12%的税
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    System.out.println(price);
}

// 使用lambda表达式
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(System.out::println);

Output:

112.0
224.0
336.0
448.0
560.0
112.0
224.0
336.0
448.0
560.0 

In the previous example, the map can be seen that the set of classes (e.g. list) converting elements. There are a reduce () function all may be combined into a single value. Map and Reduce operations are functional programming operation of the core because of its function, also known as the reduce the folding operation. In addition, reduce it is not a new operation, you may already be using it. SQL similar sum (), avg () or count () aggregate functions, in fact, reduce the operation, since they receive a plurality of values ​​and return values. API defined flow reduceh ​​() function can accept lambda expressions, and all values ​​are combined. Such classes have similar IntStream average (), count (), sum () method to do reduce built-operation, there mapToLong (), mapToDouble () method to do the conversion. This does not limit you, you can use the built-in method, you can also define your own. In this example Java Map Reduce 8, we first application of VAT to 12% of all prices, then () method used to calculate the sum reduce.

// 为每个订单加上12%的税
// 老方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double total = 0;
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    total = total + price;
}
System.out.println("Total : " + total);

// 新方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill); 

Output:

Total : 1680.0
Total : 1680.0
  • 1.7 Creating a String list by filtering

Filtration is Java developers with a common set of operations on a large scale, and now use lambda expressions and filtering large data flow API set is surprisingly simple. Providing a stream filter () method, accepts a Predicate object, i.e., a lambda expression can be passed as a filter logic. The following example is a set of Java filter with lambda expressions, it will help to understand.

// 创建一个字符串列表,每个字符串长度大于2
List<String> filtered = strList.stream().filter(x -> x.length()> 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, with regard to filter () method is a common misconception. In real life, do filter, they usually discard part, but using filter () method is to get a new list, and each element in line with the principle of filtration.

  • 1.8 application function for each element of the list

We usually need to use a function on each element of the list, such as one by one multiplied by some number, divided by a number or do other operations. These operations are suitable for map () method, may be in the form of a lambda expression conversion logic on the map () method where it can be converted to each element of the set, as shown below.

// 将字符串换成大写并用逗号链接起来
List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
System.out.println(G7Countries); 

Output:

USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA 
  • Lambda expressions vs anonymous class

Since the lambda expression will be formally replaced by an anonymous inner classes in Java code, then it is necessary for them to do a comparative analysis. A key difference is that the keyword this. this keyword anonymous anonymous class points to class, but this keyword lambda expression lambda expression that refers to class surrounded. Another difference between the two is the way the compiler. Java compiler will be compiled into class private methods lambda expressions. Using Java invokedynamic 7 bytecode instructions to the dynamic binding method.

Refer to the original link: https://zhuanlan.zhihu.com/p/33477686

Guess you like

Origin www.cnblogs.com/jlutiger/p/11127178.html