获取List中的特定元素的数量

时间:2014-01-22 19:33:04

标签: java list arraylist count size

我正在寻找一种快速方法来查找作为一个特定元素的List元素的数量:

List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("kiwi");

// I'm looking for a method as List.amountOf(Object obj):

list.amountOf("apple");     // should return 2
list.amountOf("kiwi");      // should return 1
list.amountOf("pear");      // should return 0

3 个答案:

答案 0 :(得分:11)

您可以使用Collections.frequency

int amountOfApple = Collections.frequency(list,"apple");

使用Java 8,您还可以使用流来执行此操作:

long amountOfApple = list.stream().filter(s -> "apple".equals(s)).count();

答案 1 :(得分:2)

如果您使用Eclipse Collections,则可以使用MutableBagMutableList,具体取决于订单是否对收集很重要。

// If order doesn't matter 
MutableBag<String> bag = Bags.mutable.with("apple", "banana", "apple", "kiwi");

// O(1) for bag.occurrencesOf()
Assert.assertEquals(2, bag.occurrencesOf("apple"));
Assert.assertEquals(1, bag.occurrencesOf("kiwi"));
Assert.assertEquals(0, bag.occurrencesOf("pear"));

// If order does matter 
MutableList<String> list = Lists.mutable.with("apple", "banana", "apple", "kiwi");

// O(n) for collection.count()
// Java 5 - 7
Assert.assertEquals(2, list.count(Predicates.equal("apple")));
Assert.assertEquals(1, list.count(Predicates.equal("kiwi")));
Assert.assertEquals(0, list.count(Predicates.equal("pear")));

// using Java 8 Lambdas
Assert.assertEquals(2, list.count(fruit -> fruit.equals("apple")));
Assert.assertEquals(1, list.count(fruit -> fruit.equals("kiwi")));
Assert.assertEquals(0, list.count(fruit -> fruit.equals("pear")));

// using Java 8 Method References
Assert.assertEquals(2, list.count("apple"::equals));
Assert.assertEquals(1, list.count("kiwi"::equals));
Assert.assertEquals(0, list.count("pear"::equals));

// O(n) for collection.countWith()
// using Java 8 Method References
Assert.assertEquals(2, list.countWith(Object::equals, "apple"));
Assert.assertEquals(1, list.countWith(Object::equals, "kiwi"));
Assert.assertEquals(0, list.countWith(Object::equals, "pear"));

注意:我是Eclipse Collections的提交者

答案 2 :(得分:0)

您可以使用Map

添加伪代码:

if(map.get("apple") != null){
  map.get("apple")++;
}else{
 map.put("apple",0);
}