Java’s equivalents of Func and Action

In Java 8, the equivalents are the java.util.function.Function<T, R> and java.util.function.Consumer<T> interfaces respectively. Similarly, java.util.function.Predicate<T> is equivalent to System.Predicate<T>. As mentioned elsewhere, these are interfaces instead of delegates.

Related aside: I’m currently leaning heavily on the following utility class to do LINQ-like extension method stuff:

abstract class IterableUtil {
  public static <T> Iterable<T> where(Iterable<T> items, Predicate<T> predicate) {
    ArrayList<T> result = new ArrayList<T>();
    for (T item : items) {
      if (predicate.test(item)) {
        result.add(item);
      }
    }
    return result;
  }

  public static <T, R> Iterable<R> select(Iterable<T> items, Function<T, R> func) {
    ArrayList<R> result = new ArrayList<R>();
    for (T item : items) {
      result.add(func.apply(item));
    }
    return result;
  }
}

Unlike System.Linq.Enumerable.Where<TSource> and System.Linq.Enumerable.Select<TSource, TResult> the LINQ-like methods I present here are not lazy and fully traverse the source collections before returning the result collections to the caller. Still, I find them useful for purely syntactic purposes and could be made lazy if necessary. Given

class Widget {
  public String name() { /* ... */ }
}

One can do the following:

List<Widget> widgets = /* ... */;
Iterable<Widget> filteredWidgets = IterableUtil.where(widgets, w -> w.name().startsWith("some-prefix"));

Which I prefer to the following:

List<Widget> widgets = /* ... */;
List<Widget> filteredWidgets = new ArrayList<Widget>();
for (Widget w : widgets) {
  if (w.name().startsWith("some-prefix")) {
    filteredWidgets.add(w);
  }
}

Leave a Comment

deneme bonusu veren sitelerbahis casino