2015-09-05 31 views
-1

一個字符串數組存在我有一個字符串數組是這樣的:多少具體的價值在安卓

String[] sample = { "0", "1", "0", "5", "1", "0" }; 

現在我需要知道有多少特定值這樣的數組中存在0。 所以我怎麼能得到這個?

+0

您是否正在計算數組中唯一值的數量? – kkaosninja

回答

5

希望這可以幫助你..

int count = 0; 
    String[] array = new String[]{"a", "a", "d", "c", "d", "c", "v"}; 
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(array)); 
    for (int i = 0; i < array.length; i++) { 
     count = 0; 
     for (int j = 0; j < arrayList.size(); j++) { 
      if (arrayList.get(j).equals(array[i])) { 
       count++; 
      } 
     } 
     System.out.println("Occurance of " + array[i] + " in Array is : " + count); 
    } 
2

嘗試HashMap跟蹤數組中每個單詞的出現次數。

public static void main(String[] args) { 
     String[] sample = { "0", "1", "0", "5", "1", "0" }; 
     Map<String, Integer> map = new HashMap<>(); 
      for (String s : sample) { 
       Integer n = map.get(s); 
       n = (n == null) ? 1 : ++n; 
       map.put(s,n); 
      } 

      System.out.println(map); 

    } 

輸出:(希望這是你想要的)

{1=2, 0=3, 5=1} 

的迭代地圖使用:

Iterator it = map.entrySet().iterator(); 
    while (it.hasNext()) { 
     Map.Entry pair = (Map.Entry)it.next(); 
     System.out.println(pair.getKey() + " occurs = " +  pair.getValue()+" times"); 

    } 

輸出:

1 occurs = 2 times 
0 occurs = 3 times 
5 occurs = 1 times