Count number of items with property

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

    Personally, I like using the Apache Commons Collection lib when I can. (But the one on sourceforge since it uses generics) It lets you do some pretty elegant things such as mapping lists or filtering lists (in a scheme-ish way). You would end up writing something like this:

    int count = CollectionUtils.countMatches(myList, new Predicate(){
        public boolean evaluate(Custom c){ return "Tom".equals(c.name); }
    }
    

    The only downside is that since Java doesn't have first-order functions, you have to write little objects like that Predicate instance. It would be cleaner if you could write anonymous functions. i.e. in scala, it would be this:

    val myList = List("a", "a", "b", "c", "a")
    val c = myList.count{ "a".equals(_) }  // is 3
    

提交回复
热议问题