【问题标题】:Get amount of specific element in List获取列表中特定元素的数量
【发布时间】:2014-02-13 01:27:53
【问题描述】:

我正在寻找一种快速方法来查找 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

【问题讨论】:

  • 考虑使用 Guava 的过滤类。

标签: java list arraylist count size


【解决方案1】:

您可以使用Collections.frequency

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

使用 Java 8,您还可以使用流来做到这一点:

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

【讨论】:

    【解决方案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 的提交者

    【讨论】:

      【解决方案3】:

      你可以使用Map

      添加伪代码:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多