jdk8 方法引用
方法引用:实际上是lamda函数的语法糖
有时候并不适用
我们可以讲方法引用看做一个函数指针.function pointer
方法引用分为4类:
- 类名::静态方法名
创建一个类
public class Student {
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Student(String name, int score) {
super();
this.name = name;
this.score = score;
}
public Student() {
super();
}
public static int compareStudentByScore(Student s1,Student s2) {
return s1.getScore()-s2.getScore();
}
/**
* 根据ascii 码进行比较
* @param s1
* @param s2
* @return
*/
public static int compareStudentByName(Student s1,Student s2) {
return s1.getName().compareToIgnoreCase(s2.getName());
}
}
public static void main(String[] args) {
Student s1 =new Student("zhangsan", 10);
Student s2 =new Student("lisi", 90);
Student s3 =new Student("wangwu", 50);
Student s4 =new Student("zhaoliu", 60);
List<Student> list = Arrays.asList(s1,s2,s3,s4);
// list.sort((a,b)-> Student.compareStudentByScore(a, b));
list.sort(Student::compareStudentByScore);
list.forEach(it -> System.out.println(it.getScore()));
}
输出:
10
50
60
90
- 引用名(对象名)::方法名
.
public class StudentCompare {
public int compareStudentByScore(Student s1,Student s2) {
return s1.getScore()-s2.getScore();
}
/**
* 根据ascii 码进行比较
* @param s1
* @param s2
* @return
*/
public int compareStudentByName(Student s1,Student s2) {
return s1.getName().compareToIgnoreCase(s2.getName());
}
}
StudentCompare sc = new StudentCompare();
list.sort(sc::compareStudentByName);
list.forEach(it -> System.out.println(it.getName()));
输出
lisi
wangwu
zhangsan
zhaoliu
public int compareByName(Student stu) {
return this.getName().compareToIgnoreCase(stu.getName());
}
list.sort(Student::compareByName);
list.forEach(it -> System.out.println(it.getName()));
lisi
wangwu
zhangsan
zhaoliu
compare 有俩个参数这里只有一个参数.是调用者本身做一为第一个参数传入进去
例如:
List<String> list1 = Arrays.asList("beijing","shanxi","hangzhou","ahui");
Collections.sort(list1,String::compareToIgnoreCase);
list1.forEach(System.out::println);
这里 compareToIgnoreCase 源码不传入任何参数.就是调用本身做比较
4. ### 构造方法::new
public String getString1(String string,Function<String, String> func) {
return func.apply(string);
}
System.out.println(m.getString1("hello", String::new));