Count number of items with property

后端 未结 10 2541
不思量自难忘°
不思量自难忘° 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 12:59

    You can use count() from Eclipse Collections.

    MutableList customList = Lists.mutable.empty();
    int count = customList.count(each -> "Tom".equals(each.getName()));
    

    If you can't change customList from List:

    List customList = new ArrayList<>();
    int count = ListAdapter.adapt(customList).count(each -> "Tom".equals(each.getName()));
    

    If you have a method which checks for a name you can also use countWith():

    MutableList customList = Lists.mutable.empty();
    int count = customList.countWith(Custom::isNamed, "Tom");
    
    class Custom
    {
        public int id;
        public String name;
    
        public boolean isNamed(String nameToCheck)
        {
            return nameToCheck.equals(this.name);
        }
    }
    

    Note: I am a contributor to Eclipse Collections.

提交回复
热议问题