问题参考:https://magiclen.org/ocpjp-collection-sort/
关于下列程式码,两个问题想请问版上的高手们:
问题1:于下列程式码注解line n1处,s -> s.getEAge() > 50为何无法使用method
refrence? (Emp::getEAge) > 50
问题2:于下列程式码注解line n2处,map(Emp::getEName)为何不会编译错误?
就小的理解使用method refrence时,其中之一的用法ClassName::StaticMethod
,故getEName应该必须为static method?
先谢谢版上高手回复!
class Emp {
private String eName;
private int eAge;
Emp(String eN, Integer eA) {
this.eName = eN;
this.eAge = eA;
}
public int getEAge() {
return eAge;
}
public String getEName() {
return eName;
}
}
public class Test809 {
public static void main(String[] args) {
List<Emp> li = Arrays.asList(new Emp("Sam", 20), new Emp("John", 60),
new Emp("Jim", 51));
Predicate<Emp> agVal = s -> s.getEAge() > 50; //line n1
li = li.stream().filter(agVal).collect(Collectors.toList());
Stream<String> names = li.stream().map(Emp::getEName); //line n2
names.forEach(n -> System.out.print(n + " "));
}
}