- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 163字
- 2021-07-02 19:01:57
Method reference
To improve code readability of Lambda expressions for functions having a name method reference is used. Method references have been identified in four different categories:
- Static method reference: For a static method isOdd, the method can be directly referenced as MethodReferenceExample::isOdd:
public static boolean isOdd(Integer n) { return n % 2 != 0; };
public static void main(String[] args) {
IntStream.range(1, 8).filter(MethodReferenceExample::isOdd).forEach(x->System.out.println(x));
}
- Instance method reference: For referencing an instance method, the instance of the method can be called separated by a double colon (::). Here System.out is an instance of PrintStream whose method println is being called:
//Instance Method Reference
IntStream.range(1, 8).filter(x-> x%2==0).forEach(System.out::println);
- Constructor reference: A constructor method reference can be called by adding the suffix new after :::
//Constructor Reference
TreeSet<String> hset= streamSupplier.get().collect(Collectors.toCollection(TreeSet::new));
- Instance method reference of an arbitrary object of a particular type: The following example is an instance method reference of an arbitrary object of a particular type:
System.out.println(" The sum of lengths are ::" + streamSupplier.get().map(x->x.length()).reduce(Integer::sum));

推薦閱讀
- 軟件項目估算
- R語言游戲數(shù)據(jù)分析與挖掘
- 數(shù)據(jù)結(jié)構(gòu)(Python語言描述)(第2版)
- 前端架構(gòu):從入門到微前端
- Java Web程序設(shè)計
- 快速念咒:MySQL入門指南與進(jìn)階實戰(zhàn)
- Mastering Ext JS
- PLC編程與調(diào)試技術(shù)(松下系列)
- PySide 6/PyQt 6快速開發(fā)與實戰(zhàn)
- 計算機(jī)應(yīng)用基礎(chǔ)案例教程
- 詳解MATLAB圖形繪制技術(shù)
- Android開發(fā)三劍客:UML、模式與測試
- Mastering AWS Security
- JavaScript程序設(shè)計:基礎(chǔ)·PHP·XML
- C語言程序設(shè)計教程