News for hackers. Stuff that matters.
Re:Why I absolutely love java by eneveu on Sunday February 13, 2011 @11:19AM (#2213055)
I'd do it this way, using Guava's functional programming ability + static imports where it makes sense:

  import static com.google.common.collect.Lists.*;
  import com.google.common.collect.Iterables;
  [...]
  public static void main(String[] args) {
    List<Integer> list = newArrayList(1,2,3,4);
    System.out.println(Iterables.filter(list, isEven()));
  }

  private static Predicate<Integer> isEven() {
    return new Predicate<Integer>() {
      public boolean apply(Integer input) {
        return input % 2 == 0;
      }
    };
  }
The lack of closures is seriously felt when creating the "isEven" Predicate. This will be a lot cleaner next year (?), when closures are introduced in the language. For now, we have to live with the verbosity...

It's possible to hide some of this verbosity and write clean code. For example, I often extract the function / predicate declarations to utility classes to avoid polluting the code. In this case, I would move the "isEven()" method to a "MathPredicates" utility class. The code ends up looking like:

    List<Integer> list = newArrayList(1,2,3,4);
    System.out.println(Iterables.filter(list, MathPredicates.isEven()));

There are no comments on this comment yet.