How to count the number of occurrences of an element in a List

后端 未结 22 1600
一生所求
一生所求 2020-11-22 12:25

I have an ArrayList, a Collection class of Java, as follows:

ArrayList animals = new ArrayList();
animals.add(\"bat\         


        
22条回答
  •  半阙折子戏
    2020-11-22 12:46

    ​If you use Eclipse Collections, you can use a Bag. A MutableBag can be returned from any implementation of RichIterable by calling toBag().

    MutableList animals = Lists.mutable.with("bat", "owl", "bat", "bat");
    MutableBag bag = animals.toBag();
    Assert.assertEquals(3, bag.occurrencesOf("bat"));
    Assert.assertEquals(1, bag.occurrencesOf("owl"));
    

    The HashBag implementation in Eclipse Collections is backed by a MutableObjectIntMap.

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题