When contacted Lambda expressions, the first feeling is, this is what? I actually do not understand, so start looking for information, we must understand it.
First look at a case:
@FunctionalInterface public interface MyLamda { void test1(String y); }
import demo.knowledgepoints.Lambda.inf.MyLamda; public class LambdaTest { public static void main(String[] args) { MyLamda m = (y) ->{ System.out.println("ss"+y);}; m.test1("s"); } }
operation result:
Non-Lambda way:
import demo.knowledgepoints.Lambda.inf.MyLamda; public class MyLamdaIml implements MyLamda { @Override public void test1(String y) { System.out.println("ss"+y); } public static void main(String[] args) { MyLamdaIml myLamdaIml = new MyLamdaIml(); myLamdaIml.test1("s"); } }
operation result:
Compare these two methods: using Lambda expressions obviously feeling more concise, introduced by Java8, let's take a look at the advantages and disadvantages of Lambda expressions.
1. Lambda expression syntax :() -> {}; we have seen from the above cases, this syntax, is the substitution of one implementation of the method and implementation classes.
() Which is the parameter y, {} is a method thereof, are hidden class names, method names are hidden.
2. Lambda expressions, interfaces (MyLamda) can only have one and only one abstract method. Meanwhile annotations @FunctionalInterface can be done through the compile time checking abstract methods,
Does not meet the requirements, given compiler error.
3. (y) can be written as (String y), {} which can be omitted return. And when one-line method, can be omitted {}; () there is only one parameter () may be omitted,
Most shorthand y -> System.out.println ( "ss" + y);
Know the concept of Lambda expressions, it is necessary to use the actual situation.
Case:
The Java interface has Runable comment @FunctionalInterface.
@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
then:
public class LambdaTest { public static void main(String[] args) { Runnable runnable = () -> System.out.println("线程启动"); Thread thread = new Thread(runnable); thread.start(); } }
operation result:
import java.util.Arrays; import java.util.List; public class LambdaTest { public static void main(String[] args) { System.out.println("Java 8之前:---------------------------------------------"); List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); for (String feature : features) { System.out.println(feature); } System.out.println("Java 8之后:---------------------------------------------"); List features1 Arrays.asList = ( "Lambdas,", "the Default Method,", "the API Stream", "the API a Date and Time" ); features1.forEach (n- -> System.out.println (n-)); System.out.println ( "Java 8 using a reference method is more convenient, method references indicated by the double colon :: operator, the scope resolution operator looks like a C ++" ); features1.forEach (the System.out :: the println); } }
operation result:
Java8 introducing functional programming, also provides a powerful tool categories: java.util.function, the class data set is suitable for operation as filter.
Case:
Import java.util.Arrays; Import java.util.List; Import java.util.function.Predicate; public class LambdaTest { public static void main (String [] args) { List <String> = Arrays.asList languages ( "the Java "," Scala "," C ++ "," Haskell "," Lisp " ); System.out.println ( " the first character string is J: " ); filter (languages, (STR) -> STR. startsWith ( "J" )); System.out.println ( "last character of a string:" ); filter (languages, (STR) -> str.endsWith ( "a")); System.out.println("Print all:" ); filter (languages, (str) -> to true ); System.out.println ( "do not print:" ); filter (languages, (str) -> false ); System.out.println ( "print strings longer than. 4:" ); filter (languages, (STR) -> str.length ()>. 4 ); } public static void filter (List <string> names, the Predicate <string> for condition Condition) { for (String name: names) { IF (condition.test (name)) { of System.out.print (name + "" ); } } System.out.println(); } }
operation result:
java.util.function.Predicate allows two or more of a Predicate synthesis. It provides similar logical operators AND and OR a method, called and () and or (), is used to filter incoming conditions of the process were pooled ().
Case:
Import java.util.Arrays; Import java.util.List; Import java.util.function.Predicate; public class LambdaTest { public static void main (String [] args) { List <String> = Arrays.asList names ( "the Java "," Scala "," C ++ "," Haskell "," Lisp " ); // can even be combined with Predicate and (), or () logic function // example, to find all J, length four letters of the name, you can merge two Predicate and pass Predicate <String> startsWithJ = (the n-) -> n.startsWith ( "J" ); Predicate <String> fourLetterLong = (the n-) -> n.length () 4 == ; . names.stream () filter (startsWithJ.and (fourLetterLong)) .forEach ((n-) -> of System.out.print ( "beginning of the string is" J "and is equal to the length of the character. 4:" + n-)); } }
operation result:
Functional programming concept map, changing the element values.
Case:
import java.util.Arrays; import java.util.List; public class LambdaTest { public static void main(String[] args) { // 使用lambda表达式 List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(n -> System.out.print(n+"; ")); System.out.println(); double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get(); System.out.println("Total : " + bill); } }
operation result:
Case: (filter the data to meet the conditions of formation of a new List)
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class LambdaTest { public static void main(String[] args) { List<String> strList = Arrays.asList("abc","bcd","defg","jk"); List<String> filtered = strList.stream().filter(x -> x.length()> 2).collect(Collectors.toList()); System.out.printf("原List : %s, 新list : %s", strList, filtered); } }
operation result:
Case: (map () of the conversion elements, DISTINCT () method of collection to weight )
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class LambdaTest { public static void main(String[] args) { 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); List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4); List<Integer> distinct = numbers.stream().map( i -> i*I) .distinct () the collect (Collectors.toList (.)); System.out.printf ( "Original List:% s, squared new List:% S" , Numbers, DISTINCT); } }
operation result:
Case :( maximum, minimum, and average)
Import java.util.Arrays; Import java.util.IntSummaryStatistics; Import java.util.List; public class LambdaTest { public static void main (String [] args) { // Get the number of digits, minimum, maximum, the average sum of the List <Integer> = Arrays.asList primes (2,. 3,. 5,. 7,. 11, 13 is,. 17,. 19, 23 is, 29 ); IntSummaryStatistics stats = primes.stream () mapToInt ((X) -. > X) .summaryStatistics (); System.out.println ( "maximum value of List:" + stats.getMax ()); System.out.println ( "minimum List:" + stats.getMin ()); System.out.println ("List sum:" + stats.getSum ()); System.out.println ( "List of average value:" + stats.getAverage ()); } }
operation result:
to sum up:
lambda expression:
1. simplify the code.
2. convenient set of operations.
Disadvantages:
1. Strong limitation, difficult for complex operations.
2. Set up the inconvenient problem, it is difficult to troubleshoot.