Reputation: 2797
I have a List of Objects, e.g.
public class Foo {
private String str;
private Integer i;
// Getter
}
//
List<Foo> list;
Now I want to search for e.g. all Object where String str is equal to someString
What would be the best way to archieve that? Of course I could iterate over the whole List und compare every Object with my search-String (or search-Integer, or whatever I am lookin for), but I am wondering if there is a ready solution for this (in my opinion where basic task) e.g. in the Collection-Framework or somewhere else?
Upvotes: 0
Views: 86
Reputation: 1745
If you want to use guava
you could do something like this:
Foo result = Iterables.find(list, new Predicate<Foo>() {
public boolean apply(Foo foo) { return foo.getInteger() == 3; }
});
Or in the upcoming java8
you can use lambda expressions:
list.stream()
.filter( f -> f.getInteger() == 3)
.collect(Collectors.toList());
And you won't need a 3rd party library for that :)
Upvotes: 1
Reputation: 598
Take a look at google's Guava and filters api:
https://code.google.com/p/guava-libraries/wiki/FunctionalExplained
Upvotes: 2