2015-10-09 38 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);