- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
- Related Articles
- How to use IntStream in lambdas and method references in Java?
- Explain generics and How to apply method or variable generics in Swift?
- What are the method references in Java?
- What are Unbounded wildcard w.r.t Generics method in Java?
- Bounded types with generics in Java\n
- How to use List size() method in Java With Examples?
- Generics in Java
- What are upper-bounded wildcard w.r.t Generics method in Java?
- What are lower-bounded wildcard w.r.t Generics method in Java?
- How to create an immutable class with mutable object references in Java?\n
- How to use Java substring Method?
- Reference to a static method using method references in Java8
- Reference to an instance method using method references in Java8
- What are method references in Java8?
- When to use references vs. pointers in C/C++

Advertisements