1

let's say i have a list with some elements and i want to choose all those who do not satisfy a certain condition. i was thinking about something like this:

public void choose(Condition c) {
     choose all elements that satisfy c.CheckCondition(elem)
}

however, i think it's highly unelegant and it forces to user to implement a Condition object with a certain function that will check if an element satisfies a condition. if it was c++ i would send a pointer to a function as a parameter but its not possible in java. I thought about using Comparable object but it's no good since i have to implement it in my class instead of getting it from the user.

any other elegant ideas for this problem?

thanks!

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
Asher Saban
  • 4,673
  • 13
  • 47
  • 60

2 Answers2

2

Not for now - Java 7 still does not have closures ("function pointers" in C). It may come in Java 8. In the meantime, we're stuck at writing our predicates as classes...

But you may be interested in the Guava library. It's developed by Google, and already provides classes to filter, map or transform the elements of a collection. http://code.google.com/p/guava-libraries/

Olivier Croisier
  • 6,139
  • 25
  • 34
0

I think what you propose is fairly elegant, especially when combined with generics and anonymous classes:

set.choose(new Condition<Elem>() {
  boolean checkCondition(Elem elem) {
    ...
  }
});
NPE
  • 486,780
  • 108
  • 951
  • 1,012