Count number of items with property

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

    Easier probably not. Now you could store your objects in a Map <String, List<Custom>> instead where the key is the name. To get the number of items where name == "Tom" you can then simply do:

    List<Custom> l = myMap.get("Tom");
    int count = 0;
    if (l != null) {
        count = l.size();
    }
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2021-02-13 13:11

    There is no easier solution with the standard collections. You have to iterate over the list and count the occurrences of the name.

    0 讨论(0)
  • 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<Custom>(){
        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
    
    0 讨论(0)
提交回复
热议问题