對於很多有搜索需求的功能,一般需要展示下最近n次的歷史搜索記錄,主要有以下幾個功能點:
- 最近搜索條目放在最前面,最早的搜索記錄放在最後。
- 只記錄最近n條數據,如果超過n條搜索記錄,刪除搜索時間最久遠的記錄。
- 沒有重複的搜索項,如果新搜索的關鍵字已存在,則將該關鍵字提到最前面,刪除原位置關鍵字。
- 可方便的持久化,並可以通過讀取持久化數據,恢復原紀錄歷史。
基於以上這些條件,不難看出這就是一個無重複數據的LRU stack,本來以爲java集合會有支持該需求的實現,嘗試了stack等集合類型,發現不是很好弄,最後還是採用list做一個吧,簡單方便。
Android版:
public class SearchHistoryUtil {
private LruStackUtil mLruStack = null;
public SearchHistoryUtil(int maxSize) {
this.mLruStack = new LruStackUtil(maxSize);
}
public void updateSearchHistorys(Context context, String keyWord) {
SharedPreferences sharedPreferences = context.getSharedPreferences("music_search_history",
Activity.MODE_PRIVATE);
String mKeys = sharedPreferences.getString("keys", "");
mLruStack.reset();
SharedPreferences.Editor editor = sharedPreferences.edit();
String[] tmpHistory = mKeys.split(",");
for (String i : tmpHistory) {
mLruStack.push(i);
}
mLruStack.pushHead(keyWord);
editor.putString("keys", mLruStack.getAll());
editor.apply();
}
public static String getAllHistorys(Context context) {
SharedPreferences sharedPreferences= context.getSharedPreferences("music_search_history",
Activity.MODE_PRIVATE);
String mKeys = sharedPreferences.getString("keys", "");
return mKeys;
}
public static void clearAll(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("music_search_history",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
public class LruStackUtil {
ArrayList<String> stack = null;
private int size = 0;
public LruStackUtil(int size) {
this.stack = new ArrayList<String>();
this.size = size;
}
public void pushHead(String keyWord) {
if (stack.remove(keyWord)) {
stack.add(0, keyWord);
return;
}
if (stack.size() > this.size - 1) {
stack.remove(stack.size() - 1);
stack.add(0, keyWord);
} else {
stack.add(0, keyWord);
}
}
public void push(String keyWord) {
if (stack.contains(keyWord)){
return;
}
if (stack.size() > this.size - 1) {
return;
} else {
stack.add(keyWord);
}
}
public String getAll() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < stack.size(); i++) {
str.append(stack.get(i) + ",");
}
return str.toString();
}
public void reset() {
if (stack != null) {
stack.clear();
}
}
}
其實這個實現完全沒有任何技術難度,只是儘量將改功能模塊化,接口化,方便調用。