2015-12-31 100 views
-5

我試圖找出在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出現找到。但是,我怎麼能找到其他的東西,如果我想找到bc的事件呢?有沒有辦法我可以做到這一點?我可以有很多等於功能嗎?

+0

它爲什麼倒投了? – nick

+2

您可以創建一個'HashMap '並計算每個'String'的出現次數。 – Atri

+0

hashmap不可能 – nick

回答

0
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); 

如果你想使它成爲一個通用函數,它只需要2個參數,集合和你想要的項目。

+0

亞,但集合會很好,優化選項吶? – nick

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

您必須手動迭代列表並查找不同屬性的頻率。

相關問題