使用() -> {} 替代匿名类: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(); Output:too much code, for too little to doLambda expression rocks !!
你可使用 下面语法实现Lambda:express
(params) -> expression
(params) -> statement
(params) -> { statements }编程
若是你的方法并不改变任何方法参数,好比只是输出,那么能够简写以下:swift
() -> System.out.println("Hello Lambda Expressions");ide
若是你的方法接受两个方法参数,以下:函数
(int even, int odd) -> even + odd
测试
若是你曾经作过Swing 编程,你将永远不会忘记编写事件侦听器代码。使用lambda表达式以下所示写出更好的事件侦听器的代码。google
// 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"); });
在java 8中你可使用Lambda表达式替代丑陋的匿名类。spa
features .asList(, , , ); ( feature ) { .out.println(feature); } features .asList(, , , ); features.forEach(n -> .out.println(n));features.forEach(.out::println); and
方法引用是使用两个冒号::这个操做符号。线程
为了支持函数编程,Java 8加入了一个新的包java.util.function,其中有一个接口java.util.function.Predicate是支持Lambda函数编程:
(args[]){ List languages = Arrays.(, , , , ); System..(); filter(languages, (str)->str.()); System..(); filter(languages, (str)->str.()); System..(); filter(languages, (str)->); System..(); filter(languages, (str)->); System..(); filter(languages, (str)->str.() > ); } (List names, Predicate condition) { (String names) { (condition.(name)) { System..(name + ); } } } }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 : Scala Haskell (List names, Predicate condition) { names.().((name) -> (condition.(name))) .((name) -> {System..(name + ); }); }
你能看到来自Stream API 的filter方法可以接受 Predicate参数, 可以容许测试多个条件。
java.util.function.Predicate提供and(), or() 和 xor()能够进行逻辑操做,好比为了获得一串字符串中以"J"开头的4个长度:
<> startsWithJ (n) -> n.startsWith(); <> fourLetterLong (n) -> n.length() == ; names.stream() .filter(startsWithJ.(fourLetterLong)) .forEach((n) -> .out.print( + n));
其中startsWithJ.and(fourLetterLong)是使用了AND逻辑操做。
最流行的函数编程概念是map,它容许你改变你的对象,在这个案例中,咱们将costBeforeTeax集合中每一个元素改变了增长必定的数值,咱们将Lambda表达式 x -> x*x传送map()方法,这将应用到stream中全部元素。而后咱们使用 forEach() 打印出这个集合的元素.
costBeforeTax .asList(, , , , ); ( cost ) { double price cost + .*cost; .out.println(price); } costBeforeTax .asList(, , , , ); costBeforeTax.stream().map((cost) -> cost + .*cost) .forEach(.out::println);
reduce() 是将集合中全部值结合进一个,Reduce相似SQL语句中的sum(), avg() 或count(),
// Applying 12% VAT on each purchase// 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);OutputTotal : 1680.0Total : 1680.0
Filtering是对大型Collection操做的一个通用操做,Stream提供filter()方法,接受一个Predicate对象,意味着你能传送lambda表达式做为一个过滤逻辑进入这个方法:
<> filtered strList.stream().filter(x -> x.length()> ) .collect(.toList());.out.printf(, strList, filtered); [, , , , , ], filtered list , bcd, defg
咱们常常须要对集合中元素运用必定的功能,如表中的每一个元素乘以或除以一个值等等.
<> G7 .asList(, , , , , ,); G7Countries G7.stream().map(x -> x.toUpperCase()) .collect(.joining());.out.println(G7Countries); , , , , , U.K.,
上面是将字符串转换为大写,而后使用逗号串起来。
使用Stream的distinct()方法过滤集合中重复元素。
<> numbers .asList(, , , , , , );<> distinct numbers.stream().map( i -> i*i).distinct() .collect(.toList());.out.printf(, numbers, distinct); [, , , , , , ], duplicates , , , ,
<> primes .asList(, , , , , , , , , ); stats primes.stream().mapToInt((x) -> x) .summaryStatistics();.out.println( + stats.getMax());.out.println( + stats.getMin());.out.println( + stats.getSum());.out.println( + stats.getAverage());