我有一个数组列表,一个Java的集合类,如下所示:

ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");

如您所见,animals数组列表由3个bat元素和1个owl元素组成。我想知道在Collection框架中是否有返回蝙蝠出现次数的API,或者是否有另一种方法来确定出现次数。

我发现谷歌的集合Multiset确实有一个API,返回一个元素的总出现次数。但是这只与JDK 1.5兼容。我们的产品目前是JDK 1.6,所以我不能使用它。


当前回答

使用Streams的Java 8解决方案:

long count = animals.stream().filter(animal -> "bat".equals(animal)).count();

其他回答

使用Streams的Java 8解决方案:

long count = animals.stream().filter(animal -> "bat".equals(animal)).count();

如果使用Eclipse Collections,则可以使用Bag。MutableBag可以通过调用toBag()从RichIterable的任何实现中返回。

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

Eclipse Collections中的HashBag实现由MutableObjectIntMap支持。

注意:我是Eclipse Collections的提交者。

我想知道,为什么你不能在JDK 1.6中使用谷歌的Collection API。上面这么说吗?我认为可以,不应该有任何兼容性问题,因为它是为较低版本构建的。如果它是为1.6构建的,而你运行的是1.5,情况就会有所不同。

我哪里说错了吗?

直接从列表中获取对象的出现次数:

int noOfOccurs = Collections.frequency(animals, "bat");

要在列表中获取Object集合的出现情况,重写Object类中的equals方法如下:

@Override
public boolean equals(Object o){
    Animals e;
    if(!(o instanceof Animals)){
        return false;
    }else{
        e=(Animals)o;
        if(this.type==e.type()){
            return true;
        }
    }
    return false;
}

Animals(int type){
    this.type = type;
}

调用Collections.frequency为:

int noOfOccurs = Collections.frequency(animals, new Animals(1));

Java 8 -另一种方法

String searched = "bat";
long n = IntStream.range(0, animals.size())
            .filter(i -> searched.equals(animals.get(i)))
            .count();