Java equivalent of C#’s Func

May 3, 2013 @ 11:07 pm Posted to .Net, Java by Antony Koch

If you’re wondering how to translate a .Net Func<T, T1> (up to the 16th item) into comparable java code, then here’s how. First, the C#

public class Car {
  // ID
  public string ModelId { get; set; }
}

public class Account {
  // ID
  public int Id { get; set; }
}
// some code
public void AddIdsToList<T>(Collection<T> collection, List<string> ids, Func<T, string> extractId) {
  foreach (T item in collection) {
    ids.add(extractId.Invoke(item));
  }
}

public List<string> CollectIdentifiers() {
  var car = new Car { ModelId = "Fiesta" };
  var account = new Account { Id = 45 };

  var ids = new List<string>();
  AddIdsToList(new Collection<Car>(car), ids, x => x.ModelId);
  AddIdsToList(new Collection<Account>(account), ids, x => x.Id.ToString());
}

And now, the same in Java using inner classes

public class Car {
  private String modelId;

  public Car(String modelId) {
    this.modelId = modelId;
  }

  public String getModelId() {
    return this.modelId;
  }
}

public class Account {
  private int id;

  public Account(int id) {
    this.id = id;
  }
  // ID
  public int getId() {
    return this.id;
  }
}

interface GetTheIdFunc<T> {
  String getTheId(T item);
}
// some code
public <T> void AddIdsToList(Collection<T> collection, List<string> ids, GetTheIdFunc<T> extractId) {
 for (T item : collection) {
   ids.add(extractId.getTheId(item));
 }
}

public List<string> CollectIdentifiers() {
  Car car = new Car("Fiesta");
  Account account = new Account(45);

  List<string> ids = new ArrayList<string>();
  AddIdsToList(new ArrayList<Car>(car), ids, new GetTheIdFunc<Car>() {
    public String getTheId(Car item) {
      return item.getModelId();
    }
  });
 AddIdsToList(new ArrayList<Account>(account), ids, new GetTheIdFunc<Account>() {
    public String getTheId(Account item) {
      return item.getId().toString();
    }
  });
}

Quite different but conceptually pretty clean and logical really when you consider that an interface offers a contract. Not as flexible on the fly as C#, but not a lot of extra code. Where these internal interface types should rest package-wise is an interesting one though. Any thoughts?

Leave a Reply

Your email address will not be published. Required fields are marked *