官术网_书友最值得收藏!

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));
  1. 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));
主站蜘蛛池模板: 六安市| 韶山市| 民县| 大悟县| 荥经县| 贵定县| 万盛区| 疏附县| 上林县| 黎平县| 仁布县| 南郑县| 高雄市| 平利县| 松溪县| 简阳市| 隆林| 息烽县| 榆中县| 莒南县| 潍坊市| 张家港市| 龙南县| 开封市| 和硕县| 安泽县| 沛县| 兴国县| 徐汇区| 望江县| 裕民县| 安徽省| 诏安县| 新巴尔虎左旗| 东莞市| 江孜县| 北川| 囊谦县| 噶尔县| 公安县| 德化县|