首页  

java方法引用     所属分类 java8 浏览量 1000
方法引用 操作符号

类::静态方法
对象::实例方法
类::实例方法
构造器引用 Class::new
数组引用  数组::new



Pet pet0 =  new Pet("dog",1);
List<Pet> pets = new ArrayList<>();
		
Pet pet =  new Pet("tiger",2);
pets.add(pet);
		
pet =  new Pet("cat",3);
pets.add(pet);
System.out.println(pets);
	    
// 静态方法引用 
pets.sort(Pet::compareByName);
System.out.println(pets);
	    
// 引用 指定对象的实例方法
// sayHelloTo(Pet pet) 
pets.forEach(pet0::sayHelloTo);
	    
// 引用 指定类型的实例方法
// 直接调用入参的实例方法
// void sayHello()
pets.forEach(Pet::sayHello);

// 引用构造函数
Supplier<Pet> supplier = Pet::new;
System.out.println("pet="+supplier.get());

<hr>
(Apple a) -> a.getWeight      Apple::getWeight
(str,i) -> str.substring(i)   String::substring
(String s) -> System.out.println(s)     System.out::println


<hr>
	   
public class Pet{

	public final String name;
	public final int age;

	public Pet(){
		name = "";
		age = 0;
	}
	
	public Pet(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	@Override
	public String toString(){
		return name+":"+age;
	}
	
	
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	
	public static int compareByName(Pet a,Pet b){
		return a.name.compareTo(b.name);
	}
	
	public static int compareByNameDesc(Pet a,Pet b){
		return b.name.compareTo(a.name);
	}
	
	public static int compareByAge(Pet a,Pet b){
		return Integer.compare(a.age, b.age);
	}
	
	public static int compareByAgeDesc(Pet a,Pet b){
		return Integer.compare(b.age, a.age);
	}
	
	public static int compareByNameThenAge(Pet a,Pet b) {
	    if (a.name.equals(b.name)) {
	        return Integer.compare(a.age, b.age);
	    } else {
	        return a.name.compareTo(a.name);
	    }
	}
	
	public void sayHello() {
		System.out.println(this+" sayHello ");
	}
	
	public void sayHelloTo(Pet pet) {
		System.out.println(this + " sayHelloTo "+pet.toString());
	}
	
	public void sayHelloToNull() {
		System.out.println(this + " sayHelloToNull ");
	}
	
	
}    
	    



https://gitee.com/dyyx/hellocode/tree/master/src/dyyx/java8/lambda

上一篇     下一篇
Java8 Lambda表达式排序实战

java方法引用实例

Java8 Stream 及 常见坑点

OSGI与Java模块化之路

Lambda表达式与匿名内部类的区别

Java方法调用的字节码指令