Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to find objects matching certain criteria in a java.util.List?

Tags:

java

list

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

like image 434
Allain Lalonde Avatar asked Dec 07 '22 09:12

Allain Lalonde


2 Answers

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

like image 100
oxbow_lakes Avatar answered Apr 29 '23 03:04

oxbow_lakes


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.

like image 43
Mario Fusco Avatar answered Apr 29 '23 03:04

Mario Fusco