标签:stat sum blank array lis set 返回值 create string
匿名函数
- A static method (
ClassName::methName
)- An instance method of a particular object (
instanceRef::methName
)- A
super
method of a particular object (super::methName
)- An instance method of an arbitrary object of a particular type (
ClassName::methName
)- A class constructor reference (
ClassName::new
)- An array constructor reference (
TypeName[]::new
)
System.out::println
Person::getAge
ArrayList::new
String[]::new
super::method
@Test
public void testBiConsumer (){
BiConsumer<Person, String> biConsumerRef = Person::setName;
BiConsumer<Person, String> biConsumer = (Person person, String name) -> person.setName(name);
test(Person::setAge);
test((Person a ,Integer b)->a.setAge(b));
}
public static void test(BiConsumer<Person,Integer> consumer){
Person person = new Person("1", 28);
consumer.accept(person,2);
System.out.println(person);
}
@Test
public void testObjectMethod() {
List<String> list = Arrays.asList("aaaa", "bbbb", "cccc");
//对象实例语法 instanceRef::methodName
list.forEach(this::print);
list.forEach(n-> System.out.println(n));
}
public void print(String content){
System.out.println(content);
}
@Test
public void testArray (){
IntFunction<int[]> arrayMaker = int[]::new;
// creates an int[10]
int[] array = arrayMaker.apply(10);
array[9]=10;
System.out.println(array[9]);
}
public class Example {
private String name;
Example(String name) {
this.name = name;
}
public static void main(String[] args) {
InterfaceExample com = Example::new;
Example bean = com.create("hello world");
System.out.println(bean.name);
}
interface InterfaceExample {
Example create(String name);
}
}
这里的用法可能觉得很奇怪。理解一点函数式接口与方法入参以及返回类型一样,就能将该方法赋值给该接口
这里的
Example::new
与Example create(String name)
的入参以及返回值都一样,所以可以直接赋值InterfaceExample com = Example::new;
资料
标签:stat sum blank array lis set 返回值 create string
原文地址:https://www.cnblogs.com/froggengo/p/14665399.html