Java 8 - Method References

In Java 8, we can allude a technique from class or item utilizing class::methodName type syntax.

A technique reference can be utilized to point the accompanying kinds of strategies −

  • Static methods
  • Instance methods
  • Constructors utilizing new administrator (TreeSet::new)

1 Types of technique references

Method ReferenceDescriptionMethod reference example
Reference to static methodUsed to allude static techniques from a classMath::max proportional to Math.max(x,y)
Reference to instance strategy from instanceRefer to an occurrence technique utilizing a reference to the provided objectSystem.out::println equal to System.out.println(x)
Reference to instance strategy from class typeInvoke the case technique on a reference to an article provided by the contextString::length equal to str.length()
Reference to constructorReference to a constructorArrayList::new proportionate to new ArrayList()

2. Technique reference to static strategy – Class::staticMethodName

A guide to utilize Math.max() which is static method.

List<Integer> whole numbers = Arrays.asList(1,12,433,5);
Optional<Integer> max = Math::max );
max.ifPresent(value - > System.out.println(value));



javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition