tags:

views:

333

answers:

6

I could write myself a helper class that does this when given a functor, but I was wondering if there's a better approach, or if there's something already in the standard library (seems like there should be).

Answers I've found on StackOverflow are all for C# which doesn't help me.

Thanks

+3  A: 

No - there isn't. Apache commons-collections has predicates for this sort of thing but the resultant code (using anonymous inner classes) is usually ugly and a pain to debug.

Just use a basic for-loop until they bring closures into the language

oxbow_lakes
Ok, I keep hearing conflicting information on this point: are closures in Java 7 or not? I see some pages saying they didn't make the cut and others saying they did.
jasonmp85
I think at the moment the answer is that, yes, they will probably make it. Google Neal Gafter for more info!
oxbow_lakes
+1  A: 

There is JXPath.

01
+1  A: 

You can try Quaere. I didn't use it but it looks interesting.

+1  A: 

The Google Collection Library offers this kind of helper method, a bit more cleanly than commons-collections.

Dov Wasserman
The "cleanliness" is a result of the Google collections lib being generics-aware, unlike commons collections.
Don
+3  A: 

By using the lambdaj library, for example you could find the top reputation users as it follows:

List<User> topUsers = 
    select(users, having(on(User.class).getReputation(), greaterThan(20000)));

It has some advantages respect the Quaere library because it doesn't use any magic string, it is completely type safe and in my opinion it offers a more readable DSL.

Mario Fusco
+3  A: 

Querydsl provides this functionality as well via its Collections module. I am biased since I am the maintainer of the module, but I believe given the constraints of Java 6 this is an option.

With Java 7 there will be closures which enable filtering via closures, which makes usage of external libraries less necessary.

Timo Westkämper
and another spam...
gbn
Why is this being flagged as spam where as other very similar answers aren't? This is just as valid as some of the other answers.
Yacoby
@Timo You may be interested in this thread on meta: http://meta.stackoverflow.com/questions/50038/it-doesnt-matter-what-the-question-is-theres-only-one-answer
Yacoby