java基础-匿名函数
2021/4/16 12:29:09
本文主要是介绍java基础-匿名函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
匿名函数
::操作符
- 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
BiConsumer
@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); }
Consumer
@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;
资料
官网说明
这篇关于java基础-匿名函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?