一个记录最近搜索历史的LRU实现
生活随笔
收集整理的這篇文章主要介紹了
一个记录最近搜索历史的LRU实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
對(duì)于很多有搜索需求的功能,一般需要展示下最近n次的歷史搜索記錄,主要有以下幾個(gè)功能點(diǎn):
- 最近搜索條目放在最前面,最早的搜索記錄放在最后。
- 只記錄最近n條數(shù)據(jù),如果超過(guò)n條搜索記錄,刪除搜索時(shí)間最久遠(yuǎn)的記錄。
- 沒(méi)有重復(fù)的搜索項(xiàng),如果新搜索的關(guān)鍵字已存在,則將該關(guān)鍵字提到最前面,刪除原位置關(guān)鍵字。
- 可方便的持久化,并可以通過(guò)讀取持久化數(shù)據(jù),恢復(fù)原紀(jì)錄歷史。
基于以上這些條件,不難看出這就是一個(gè)無(wú)重復(fù)數(shù)據(jù)的LRU stack,本來(lái)以為java集合會(huì)有支持該需求的實(shí)現(xiàn),嘗試了stack等集合類型,發(fā)現(xiàn)不是很好弄,最后還是采用list做一個(gè)吧,簡(jiǎn)單方便。
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();}} }其實(shí)這個(gè)實(shí)現(xiàn)完全沒(méi)有任何技術(shù)難度,只是盡量將改功能模塊化,接口化,方便調(diào)用。
總結(jié)
以上是生活随笔為你收集整理的一个记录最近搜索历史的LRU实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IDEA详细配置与使用
- 下一篇: HTTP协议特点