java8新特性 (λ、stream 与 默认接口方法)

  

1.lambda

λ表达式本质上是一个匿名方法,用来方便地实现函数接口。也就是说,λ表达式主要用于替换以前广泛使用的内部匿名类。 
让我们来看下面这个例子:
    public int add(int x, int y) {
        return x + y;
    }
转成λ表达式后是这个样子:
    (int x, int y) -> x + y;
参数类型也可以省略,Java编译器会根据上下文推断出来:
    (x, y) -> x + y; //返回两数之和
或者
    (x, y) -> { return x + y; } //显式指明返回值

λ表达式由三部分组成:参数列表箭头(->),以及一个表达式或语句块

λ表达式的类型,叫做“目标类型(target type)。λ表达式的目标类型是“函数接口(functional interface),这是Java8新引入的概念。它的定义是:一个接口,如果只有一个显式声明的抽象方法,那么它就是一个函数接口。一般用@FunctionalInterface标注出来(也可以不标)。举例如下:
public interface Runnable { void run(); }
public interface Comparator<T> { int compare(T o1, T o2);}

href="https://code.youkuaiyun.com/assets/embed-df3d4903cf8e7d8df1c7eddf8fed1500.css" media="screen" rel="stylesheet" type="text/css" />
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
              
import java.util.Arrays ;
import java.util.Collections ;
import java.util.List ;

public class A {
public int a = 10 ;

public static void main ( String [] args ) {
List < String > namesList = Arrays . asList ( "peter" , "anna" , "mike" ,
"xenia" , "xiaoMing" );
Collections . sort ( namesList , ( a , b ) -> ( a . length () - b . length ()));
System . out . println ( namesList );
namesList . forEach (( o ) -> {
System . out . println ( o );
});

System . out . println ();
new Thread (() -> {
System . out . println ( "Hello Lambda!" );
}). start ();

//anonymous class
Thread oldSchool = new Thread ( new Runnable () {
@Override
public void run () {
System . out . println ( "This is from an anonymous class." );
}
});
oldSchool . start ();
}
}
/*
* [anna, mike, peter, xenia, xiaoMing] anna mike peter xenia xiaoMing
*
* Hello Lambda! This is from an anonymous class.
*/
来自CODE的代码片
lambda.java
lambda不是匿名内部类的语法糖,见下。
  1. package com.yichudu;  
  2.   
  3. public class A {  
  4.     public static void main(String[] args) {  
  5.         //使用匿名内部类,编译后会有A$1.class的存在  
  6.         Thread t1=new Thread(new Runnable() {  
  7.               
  8.             @Override  
  9.             public void run() {  
  10.                 System.out.print(123);  
  11.                   
  12.             }  
  13.         } );  
  14.         //use lambda expression,no extra class generates.  
  15.         Thread t2=new Thread(()->{System.out.print(123);});  
  16.     }  
  17. }  
package com.yichudu;

public class A {
	public static void main(String[] args) {
		//使用匿名内部类,编译后会有A$1.class的存在
		Thread t1=new Thread(new Runnable() {
			
			@Override
			public void run() {
				System.out.print(123);
				
			}
		} );
		//use lambda expression,no extra class generates.
		Thread t2=new Thread(()->{System.out.print(123);});
	}
}


2.stream

Stream<E> java.util.Collection. stream()
返回Stream对象。
Stream<T> java.util.stream.Stream. filter(Predicate<? super T> predicate)
从stream中过滤元素,返回的stream由与谓词匹配的元素组成。
void java.util.stream.Stream. forEach(Consumer<? super T> action)
对stream中的每一个元素执行action。
boolean java.util.function. Predicate. test(T t)
Predicate接口中的方法,评估给定元素是否满足谓词。
void java.util.function. Consumer. accept(T t)
Consumer接口中的方法,此方法对给定的元素进行操作。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
                        
public class Apple {
public int weight = 2 ;
public Apple (){}
public Apple ( int x ){
weight = x ;
}
public static void main ( String [] args ) {
List < Apple > fruits = Arrays . asList ( new Apple (), new Apple (), new Apple ( 3 ));
//过滤出重量为2的苹果,并将这些苹果重量设为1
fruits . stream (). filter ( s -> s . weight == 2 ). forEach ( s -> s . weight = 1 );
//得到最沉的苹果
Apple heaviestApple = fruits . stream (). max (( a , b )->( a . weight - b . weight )). get ();
heaviestApple . weight = 4 ;
//求出所有苹果的重量之和
int sum = fruits . stream (). mapToInt ( o -> o . weight ). sum ();
//输出验证
fruits . forEach ( o -> System . out . print ( o . weight ));
}
}
// 114
来自CODE的代码片
stream.java

3.默认接口方法

通过default关键字给接口的方法提供默认实现。
这样与抽象类的普通方法就差别不大了。
java.util.Collection接口的源代码含有下面的默认接口实现。
  default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值