Kat*_*Kat 5 java android arraylist
我有一个String[],originalStringArray其中有重复的.所以{"dog","cat","dog","fish","dog","cat"}.
我想创建一个只返回恰好发生一定次数的字符串的函数.在这里,如果我说3,它将返回"狗"而不是"猫".
这是我目前的代码:
public ArrayList<String> returnMultiples(String[] originalStringArray,int requiredCount){
ArrayList<Integer> mCount = new ArrayList<>();
List<String> list = Arrays.asList(originalStringArray);
ArrayList<String> result = new ArrayList<>();
// Count occurrences in original string
for(String item: originalStringArray){
mCount.add(Collections.frequency(list,item));
}
// If frequency is equal to count, add to array list
for(int i=0; i<mCount.size(); i++){
if(mCount.get(i) == requiredCount){
result.add(originalStringArray[i]);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,我在某处读到了Collections库非常慢并且拖动,并且似乎可以使用HashSets和表来减少此方法.不幸的是,我对如何做到这一点感到很茫然.有一个更好的方法吗?
需要某种地图来执行此操作。这是使用 HashMap 编写的示例:
public ArrayList<String> returnMultiples(String[] array, int min){
HashMap<String, Integer> counts = new HashMap<String, Integer>();//instantiate a new HashMap
//loop through the array and count the occurrences of each different string in the array
for(int i = 0; i < array.length; i++){
String word = array[i];
if(counts.containsKey(word))
counts.put(word, counts.get(word) + 1);
else
counts.put(word, 1);
}
ArrayList<String> multiples = new ArrayList<String>();
//check if any of the words occur >= min times. if so, add them to the returning list.
for(String key : counts.keySet()){
if(counts.get(key) >= min){
multiples.add(key);
}
}
return multiples;//return the list we just created of the desired strings
}
Run Code Online (Sandbox Code Playgroud)
根据字符串的长度,HashMap 比使用集合更有效,尽管差异几乎可以忽略不计。
| 归档时间: |
|
| 查看次数: |
523 次 |
| 最近记录: |