2015-10-09 37 views
0

我有一個StringListList,我想在Spinner或下拉菜單中顯示,但主要發生的是我有字符串重複,我想要做的是搜索arrayList的相似之處,如果它發現一個字符串例如「Hello World」在arrayList中出現7次,移除其他6並將其分配給7以表明它發生了7次,所以我的新字符串將是「Hello world (7)」,任何人都可以幫我,我怎麼能在我下面的代碼來實現這一點:如何搜索ArrayList中的相似

for(int i = 0; i < timesCalleddb.getAllTimesCalled(missedCall.getNumber()).size(); i++) 
    { 

     if(timesCalleddb.getAllTimesCalled(missedCall.getNumber()).get(i) == 
       timesCalleddb.getAllTimesCalled(missedCall.getNumber()).get(i+1)) 
     { 
      //where am guessing the implementation my problem should be 
     } 

    } 

回答

2

您應該考慮使用地圖數據結構,因爲你必須存儲櫃檯,否則,哈希集合將是完美的:

ArrayList<String> strs = ...; 

HashMap<String, Integer> counter = new HashMap<String, Integer>(); 

for(String s : strs) { 
    counter.put(s, counter.get(s) == null ? 1 : counter.get(s) + 1); 
} 

for(String s : counter.keySet()) { 
    System.out.println(s + " (" + counter.get(s) + ")"); 
} 
0

你可以做到以下幾點:

  1. 遍歷List並作出HashMap<String, Integer>指示每個String出現多少次。
  2. 使用list = new ArrayList<String>(new LinkedHashSet<String>(list));刪除List中的重複項。使用LinkedHashSet表示訂單已保存。
  3. 通過循環List並添加任何stringstring + " (" + map.get(string) + ")"取決於建立了一個新的Listmap.get(string)1或超過1
0

要從List刪除重複String,使用以下:

List<String> arrayList = new ArrayList<>(); 
// Your elements must be added to the arrayList, before progressing to the next step. 
Set<String> set = new HashSet<>(); 
set.addAll(arrayList); 

// Code for getting count of each String 
int count = 0; 
List<Integer> arrayListCount = new ArrayList<>(); 
for (Iterator<String> it = set.iterator(); it.hasNext();) { 
    String str = it.next(); 
    arrayListCount.add(count , 0); 
    for(int i = 0; i < arrayList.size(); i++){ 
     String s = arrayList.get(i); 
     if (str.equals(s)) { 
      arrayListCount.set(count , arrayListCount.get(count) + 1); 
     }     
    } 
    count++; 
} 
// Code for getting count ends here 

arrayList.clear(); 
arrayList.addAll(set); 

注:List的序列將不被保留。

希望幫助!!!

+0

但我如何跟蹤一個特定的字符串重複多少次? –

+1

@ChromeLandos對不起,我錯過了那部分,但我已經對答案進行了編輯。但是我仍然建議你使用'HashMap'。 –

0

您可以使用此代碼來過濾您根據特定字符串CustomList列表。如果要計算出現次數,可以在循環中添加一些計數器。

List<MyCustomObject> arrayList = new ArrayList<>(); 
List<MyCustomObject> result = new ArrayList<>(); 

Set<String> set = new HashSet<>(); 
for(MyCustomObject item : arrayList) { 
    if(set.add(item.getSomeString()) { 
     resultArray.add(item); 
    } 
} 
arrayList.clear(); 
arrayList.addAll(result);