
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Method References with Generics in Java
The method references are introduced in Java 8 similar to lambda expression. It can allow us to reference methods or constructors without executing them. The method references and lambda expressions require a target type that consists of a compatible functional interface. We can also use a method reference with generic classes and generic methods in java.
Example
interface MyFunc<T> { int func(T[] vals, T v); } class MyArrayOps { static<T> int countMatching(T[] vals, T v) { int count = 0; for(int i=0; i < vals.length; i++) if(vals[i] == v) count++; return count; } } public class GenericMethodRefTest { static<T> int myOp(MyFunc f, T[] vals, T v) { return f.func(v als, v); } public static void main(String args[]) { Integer[] vals = { 1, 2, 3, 4, 2, 3, 4, 4, 5 }; String[] strs = { "One", "Two", "Three", "Two" }; int count; count = myOp(MyArrayOps :: countMatching, vals, 4); System.out.println("vals contains " + count + " 4s"); count = myOp(MyArrayOps :: countMatching, strs, "Two"); System.out.println("strs contains " + count + " Twos"); } }
Output
vals contains 3 4s strs contains 2 Twos
Advertisements