Original: http://jobar.iteye.com/blog/2023477
10 examples of lambda expressions in Java8
Example 1 implementing the Runnable interface with a lambda expression
Java Code Collection Code
Before Java 8:
New Thread (New Runnable () {
@Override
public void Run () {
System.out.println ("Before Java8, too much code for too little");
}
}). Start ();
Java 8:
New Thread ((), System.out.println ("in Java8, Lambda expression Rocks!"). Start ();
Output:
Too much code, for too little
LAMBDA expression Rocks!!
This example allows us to learn how lambda expressions are written in Java8:
(parameters)-expression
Statement (parameters)
(parameter), {statement}
For example, if your method only prints information in the console, you can write:
Java Code Collection Code
() System.out.println ("Hello Lambda Expressions");
If your method receives two parameters, then:
Java Code Collection Code
(int even, int odd), even + odd
Incidentally, it is generally possible to keep variables concise in lambda expressions. This will keep your code short and stay within one line. So like the above code can choose variable names like a, b or X, Y and so on, compared to even and odd to be better.
Example 2 writing an event listener with a lambda expression
If you have used the swing API, then there is the event listener code, which is a classic example of using anonymous classes. Now we can use lambda expressions to describe better event-handling code.
Java Code Collection Code
Before 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 ");
});
Another common place to use anonymous classes is to provide a custom comparator interface implementation for the Collections.sort () method. This place can also be used with lambda expressions.
Example 3 A list iteration with a lambda expression
Java Code Collection Code
Prior Java 8:
List features = Arrays.aslist ("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature:features) {
SYSTEM.OUT.PRINTLN (feature);
}
In Java 8:
List features = Arrays.aslist ("Lambdas", "Default Method", "Stream API", "Date and Time API");
Features.foreach (n-System.out.println (n));
It is better to use the Java8 method reference, which is done by the::(double colon) operator, and looks like a scope operator in C + +
Java Code Collection Code
Features.foreach (System.out::p rintln);
Output:
Lambdas
Default Method
Stream API
Date and Time API
Example 4 using lambda expressions and functional interfaces predicate
In addition to providing functional programming language-level support, JAVA8 also adds a new package java.util.function. It contains a number of classes to support Java functional programming. One of these is the predicate interface, which uses this interface and the lamb expression to add more dynamic behavior to the API method with less code.
The following is an example of the use of predicate, which shows the many commonalities of filtering collection data.
Java Code Collection Code
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 + "");
}
}
}
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
Java Code Collection Code
Better Way
public static void filter (List names, predicate condition) {
Names.stream (). Filter ((name), (condition.test (name)). ForEach (name), {
SYSTEM.OUT.PRINTLN (name + "");
});
}
You can see that the filter method of the Stream API also accepts a predicate, which means that we can replace our custom filter () method directly with inline code. This is where the power of lambda expressions is. In addition to the predicate interface can also test multiple conditions, will be described in the following example.
Example 5:LAMBDA expression combined with predicate
As the last example says, predicate allows you to combine more than two conditions, which provide a similar logic and/or operation and (), or (), and XOR (), which can be used to combine multiple conditions passed into the filter method. For example, to get all languages that start with J and have four-character lengths, you can define two separate predicate instances to cover each condition and then combine them with the and method. See Example:
Java Code Collection Code
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 a ' J ' and four letter long is: "+ N)";
Similar can be used with OR or XOR. This example also emphasizes the importance of using predicate alone or on an as-needed basis. In short, with the advantages of predicate and lambda expressions, you can write less and do more.
Example 6 map and reduce example
6.1 map
In this example, we want to add each element of Costbeforetax to their VAT. Pass a lambda expression to the map method to apply it to each element, and then print the result with foreach.
Java Code Collection code
//without lambda expressions:
List costbeforetax = arrays.aslist (100, 200, 300, 400, 500);
for (Integer cost:costbeforetax) {
Double price = Cost +. 12*cost;
System.out.println (price);
}
//with LAMBDA expression:
List costbeforetax = arrays.aslist (100, 200, 300, 400, 500);
Costbeforetax.stream (). Map (cost), Cost +. 12*cost). ForEach (System.out::p rintln);
Output
112.0
224.0
336.0
448.0
560.0
112.0
224.0
336.0
448.0
560.0
6.2 Reduce br> there's another function. Reduce can convert all values to a value. The map and reduce operations are at the heart of functional programming, and reduce is also known as a collapse operation. Reduce is not a new operation, and some of the aggregate functions we use in SQL, such as Sum,avg,count, are actually also reduce operations, because they also operate on multiple values and return a value. The Stream API defines the reduce function, which can accept a lambda expression and then combine all the values. The stream class like Intstream has built-in methods like average (), count (), sum (), Maptolong (), maptodouble (), and so on. We can also customize it with built-in methods.
Java Code Collection code
//old-to:
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:" + all);
//New-to:
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
Example 7 Creating a string with filter list
Filtering large collections in Java development is a common operation. Using lambda expressions and the stream API makes the operation easy to understand.
Stream provides a filter () method that accepts a predicate object. This means that you can pass a lambda expression as the filter logic, see example:
Java Code Collection Code
Create a string that is longer than two characters list
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]
Example 8 applying a function to each list element
We often encounter this situation in our work: to make certain actions for each element in the list, such as multiplying or dividing by a value. These operations are as good as the map method, and we can pass the transformation logic to the map method with a lambda expression to apply to each element:
Capitalize the string and connect it with commas.
Java Code Collection Code
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
Example 9 copying different values to a child list
This example demonstrates how to use the distinct method of the stream class to filter duplicate values into the collection.
Java Code Collection Code
list<integer> numbers = arrays.aslist (9, 10, 3, 4, 7, 3, 4);
list<integer> distinct = Numbers.stream (). Map (i->i*i). DISTINCT (). Collect (Collectors.tolist ());
System.out.printf ("Original List:%s, Square without duplicates:%s%n", numbers, distinct);
Output:
Original List: [9, 3, 4, 7, 3, 4], Square without duplicates: [81, 100, 9, 16, 49]
Example 10 calculates the maximum, minimum, and average values of the elements in the list
In the stream class like Intstream, Longstream and Doublestream have a very useful method Summarystattics (), return intsummarystatistics, Longsummarystatistics or doublesummarystatistics It describes the statistics of the elements in this stream. In the following example, we use this method to calculate the sum of the maximum and minimum values in a list and the mean values:
Java Code Collection Code
List<integer> primes = arrays.aslist (2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
Intsummarystatistics stats = Primes.stream (). Maptoint ((x), X). Summarystatistics ();
System.out.println ("highest prime number in List:" + Stats.getmax ());
System.out.println ("Lowest prime number in List:" + stats.getmin ());
System.out.println ("Sum of all prime numbers:" + stats.getsum ());
System.out.println ("Average of all prime numbers:" + stats.getaverage ());
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
Java8 10 Examples of lambda expressions (RPM)