How to use method references with Generics in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Dec-2019 15:12:54
Advertisements