【问题标题】:Find the number of times a specific element occurs in an Array list查找特定元素在 Array 列表中出现的次数
【发布时间】:2015-12-31 02:59:07
【问题描述】:

我试图找出一个字符串在ArrayList 中出现了多少次。我设法通过使用Collections.frequency(list,object); 找到了

public class Main {

    public static void main(String[] args) {
        ArrayList<Main> d = new ArrayList<Main>();

        Main m = new Main();
        m.setA("a");
        d.add(m);

        Main m11 = new Main();
        m11.setA("a");
        d.add(m11);

        Main m111 = new Main();
        m111.setA("a");
        d.add(m111);

        int c = Collections.frequency(d, m11);
        System.out.println(c);
    }

    private String a,b,c;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    @Override
    public boolean equals(Object o) {
        return a.equals(((Main)o).a);
    }     
}

在上面的代码中,我设法找到了a。但是我怎样才能找到其他东西,比如如果我想找到 bcalso 的出现?有什么办法可以做到吗?可以有多个equals函数吗?

【问题讨论】:

  • 您可以创建一个HashMap&lt;String, Integer&gt;,并统计每个String的出现次数。
  • 哈希图不可能
  • user3029017 和 Atri - 两种逻辑的组合将为您提供您想要的确切结果。

标签: java android arraylist collections


【解决方案1】:

frequency 的实现。

public static int frequency(Collection<?> c, Object o) {
    int result = 0;
    if (o == null) {
        for (Object e : c)
            if (e == null)
                result++;
    } else {
        for (Object e : c)
            if (o.equals(e))
                result++;
    }
    return result;
}

所以这适用于 equals 方法,你不能有多个 equals

您必须手动遍历列表并找到不同属性的频率。

【讨论】:

    【解决方案2】:
    ArrayList<Main> d = new ArrayList<Main>();
    
    int counter = 0;
    foreach( var item in d )
    {
       if( item = "The string you desire" )
       {
           counter += 1;
       }
    }
    
    // This is the total count of the string you wanted in the collection
    console.write(counter);
    

    如果你想让它成为一个通用函数,它只需要两个参数,集合和你想要的项目。

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2015-08-22
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多