使用() -> {} 替代匿名類:java
//Before Java 8: new Thread(new Runnable() { @Override public void run() { System.out.println("Before Java8 "); } }).start(); //Java 8 way: new Thread( () -> System.out.println("In Java8!") ).start();
你可使用 下面語法實現Lambda:express
(params) -> expression
(params) -> statement
(params) -> { statements }編程
若是你的方法並不改變任何方法參數,好比只是輸出,那麼能夠簡寫以下:ide
() -> System.out.println("Hello Lambda Expressions");函數
若是你的方法接受兩個方法參數,以下:測試
(int even, int odd) -> even + oddspa
若是你曾經作過Swing 編程,你將永遠不會忘記編寫事件偵聽器代碼。使用lambda表達式以下所示寫出更好的事件偵聽器的代碼線程
在java 8中你可使用Lambda表達式替代醜陋的匿名類code
// Before Java 8: JButton show = new JButton("Show"); show.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("without lambda expression is boring"); } }); // Java 8 way: show.addActionListener((e) -> { System.out.println("Action !! Lambda expressions Rocks"); });
//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)); //方法引用是使用兩個冒號::這個操做符號 features.forEach(System.out::println); Output: Lambdas Default Method Stream API Date and Time API
爲了支持函數編程,Java 8加入了一個新的包java.util.function,其中有一個接口java.util.function.Predicate是支持Lambda函數編程:orm
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 //Even better public static void filter(List names, Predicate condition) { names.stream().filter((name) -> (condition.test(name))) .forEach((name) -> {System.out.println(name + " "); }); }
你能看到來自Stream API 的filter方法可以接受 Predicate參數, 可以容許測試多個條件
java.util.function.Predicate提供and(), or() 和 xor()能夠進行邏輯操做,好比爲了獲得一串字符串中以"J"開頭的4個長度:
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));
其中startsWithJ.and(fourLetterLong)是使用了AND邏輯操做
最流行的函數編程概念是map,它容許你改變你的對象,在這個案例中,咱們將costBeforeTeax集合中每一個元素改變了增長必定的數值,咱們將Lambda表達式 x -> x*x傳送map()方法,這將應用到stream中全部元素。而後咱們使用 forEach() 打印出這個集合的元素.
// 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::println); Output 112.0 224.0 336.0 448.0 560.0 112.0 224.0 336.0 448.0 560.0
reduce() 是將集合中全部值結合進一個,Reduce相似SQL語句中的sum(), avg() 或count()
// Old way: 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); // New way: 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
Filtering是對大型Collection操做的一個通用操做,Stream提供filter()方法,接受一個Predicate對象,意味着你能傳送lambda表達式做爲一個過濾邏輯進入這個方法:
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]
咱們常常須要對集合中元素運用必定的功能,如表中的每一個元素乘以或除以一個值等等
下面是將字符串轉換爲大寫,而後使用逗號串起來
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
使用Stream的distinct()方法過濾集合中重複元素。
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, 10, 3, 4, 7, 3, 4], Square Without duplicates : [81, 100, 9, 16, 49]
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