Count number of items with property

后端 未结 10 2538
不思量自难忘°
不思量自难忘° 2021-02-13 12:18

I have list List where Custom is like

class Custom{
    public int id;
    public String name;
}

How to

10条回答
  •  走了就别回头了
    2021-02-13 13:11

    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 nameIs(final String name) {
        return new Predicate() {
            @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.

提交回复
热议问题