Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of items with property

Tags:

java

list

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 ?

like image 782
Damir Avatar asked Feb 06 '12 18:02

Damir


2 Answers

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();
like image 115
matvei Avatar answered Sep 19 '22 22:09

matvei


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.

like image 26
Anthony Accioly Avatar answered Sep 18 '22 22:09

Anthony Accioly