Java Lambda Expression Method References with Generics

Introduction

We can use method references with generic classes and generic methods.


interface MyFunc<T> {
  int func(T[] vals, T v);
}

class MyArrayOps {
  static <T> int count(T[] vals, T v) {
    int count = 0;

    for (int i = 0; i < vals.length; i++)
      if (vals[i] == v)
        count++;/*w  ww.j a  v  a 2  s.c  o m*/

    return count;
  }
}

public class Main {

  static <T> int myOp(MyFunc<T> f, T[] vals, T v) {
    return f.func(vals, 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::<Integer>count, vals, 4);
    System.out.println("vals contains " + count + " 4s");

    count = myOp(MyArrayOps::<String>count, strs, "Two");
    System.out.println("strs contains " + count + " Twos");
  }
}



PreviousNext

Related