Discuss / Java / lambda和方法的引用,虽然还没弄懂但是好像会用了

lambda和方法的引用,虽然还没弄懂但是好像会用了

Topic source
public class Main {

	public static void main(String[] args) {
		List<Person> persons = List.of(new Person("小明", 88), new Person("小黑", 62), new Person("小白", 45),
				new Person("小黄", 78), new Person("小红", 99), new Person("小林", 58));
		// 请使用filter过滤出及格的同学,然后打印名字:
		persons.stream()
		.filter(p -> p.score >= 60)
		.map(s -> s.name)
		.forEach(System.out::println);
	}
}

class Person {
	String name;
	int score;

	Person(String name, int score) {
		this.name = name;
		this.score = score;
	}
}

随风曦457

#2 Created at ... [Delete] [Delete and Lock User]

个人理解,lambda就是定义了一个函数,方法引用实际也是传了个方法,两个应该是等价的。

为了不破坏已有的java体系,使用接口函数注解来声明了这里的入参,实际是想说明这里要传入一个方法,当然使用原有的java体系做法也行(构造一个类,实现这个接口里的方法,实例化后传入,当做入参)。

🌙

#3 Created at ... [Delete] [Delete and Lock User]

老哥,学习了,map用的好


  • 1

Reply