I have list List<Custom>
where Custom
is like
class Custom{
public int id;
public String name;
}
How to get number of items which have name "Tom" ? Is there easier way than a for loop ?
This can now be done easily with Java 8 streams — no extra libraries required.
List<Custom> list = /*...*/;
long numMatches = list.stream()
.filter(c -> "Tom".equals(c.name))
.count();
If you are going to filter by name in several places, and particularly if you are going to chain that filter with others determined at runtime, Google Guava predicates may help you:
public static Predicate<Custom> nameIs(final String name) {
return new Predicate<Custom>() {
@Override public boolean apply(Custom t) {
return t.name.equals(name);
}
};
}
Once you've coded that predicate, filtering and counting will take only one line of code.
int size = Collections2.filter(customList, nameIs("Tom")).size();
As you can see, the verbose construction of a predicate (functional style) will not always be more readable, faster or save you lines of code compared with loops (imperative style). Actually, Guava documentation explicitly states that imperative style should be used by default. But predicates are a nice tool to have anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With