問題參考: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 + " "));
}
}