對(duì)List對(duì)象列表屬性值的快速搜索

對(duì)于數(shù)據(jù)的搜索已有很多成熟的方案,比如Apace Lucene框架,結(jié)合ikanalyer等分詞器能實(shí)現(xiàn)很復(fù)雜和高效的搜索,或直接使用sql語(yǔ)言對(duì)數(shù)據(jù)庫(kù)關(guān)鍵字進(jìn)行搜索等。

但這些搜索都很重,對(duì)于已經(jīng)加載完成的數(shù)據(jù)列表并不適用。

比如有這樣一個(gè)需求:已經(jīng)加載了一個(gè)班的學(xué)生在一個(gè)List<Student>列表中,要根據(jù)學(xué)生和姓名和住址做一個(gè)模糊搜索。因?yàn)閿?shù)據(jù)已經(jīng)加載到List中,存在于內(nèi)存中,若再?gòu)臄?shù)據(jù)庫(kù)或網(wǎng)絡(luò)上去使用關(guān)鍵字取值并不是很優(yōu)的方案。而一般做法是在查找關(guān)鍵字里,遍歷整個(gè)列表逐個(gè)匹配,但若是如手機(jī)上做逐個(gè)輸入搜索的話會(huì)產(chǎn)生大量的循環(huán)操作,效率很低。

為此,今天分享一種比較對(duì)List列表比較高效的搜索方式。

思路:
1、傳入數(shù)據(jù)源List,并指定要搜索的字段;將這些字段的值拼接成一個(gè)字符串,并保存每個(gè)對(duì)象的值的起始和結(jié)束位置:
2、搜索時(shí),先使用正則表達(dá)式在保存的搜索字符串找到位置,再利用這些位置在索引數(shù)據(jù)數(shù)組中找到對(duì)應(yīng)對(duì)象索引;

具體實(shí)現(xiàn):

package com.fansion;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FSearchTool {
    private StringBuffer mKeyWordString = new StringBuffer();
    private List<Object> mSearchObjs = new ArrayList<>();
    private int[] mIndexes;

    public FSearchTool(List<? extends Object> objects, String... fields) throws Exception {
        super();
        init(objects, fields);
    }

    private void init(List<? extends Object> objs, String... fields) throws Exception {
        if (objs != null) {
            mKeyWordString.setLength(0);
            mSearchObjs.clear();
            mSearchObjs = new ArrayList<>(objs);
            mIndexes = new int[mSearchObjs.size() * 2];
            int index = 0;
            for (int i = 0; i < mSearchObjs.size(); i++) {
                Object info = mSearchObjs.get(i);
                // 指定要搜索的字段
                String searchKey = getSearchKey(info, fields);
                // 將該字符串在總字符串中的起終位置保存下來,位置是索引值而非長(zhǎng)度
                int length = mKeyWordString.length();
                mIndexes[index] = length;
                mKeyWordString.append(searchKey);
                length = mKeyWordString.length();
                index++;
                // 保存新加搜索字段的索引值
                mIndexes[index] = (length > 0) ? length - 1 : 0;
                index++;
            }
        }
    }

    /**
     * 通過反射從對(duì)象中取出指定字段的值
     */
    private String getSearchKey(Object obj, String... fields) throws Exception {
        StringBuilder searchKeys = new StringBuilder();
        Class<? extends Object> clazz = obj.getClass();
        try {
            for (String str : fields) {
                // 搜索字段使用空格隔開
                Field f = clazz.getDeclaredField(str);
                f.setAccessible(true);
                Object val = f.get(obj);
                searchKeys.append(val).append(" ");
                f.setAccessible(false);
            }
        } catch (Exception e) {
            throw new Exception("取值異常:" + e.getMessage());
        }
        return searchKeys.toString();
    }

    /**
     * 搜索結(jié)果
     *
     * @param keyWords
     *            搜索的關(guān)鍵字,要去掉首尾的空格
     * @return 返回搜索到的對(duì)象
     */
    public List<Object> searchTasks(String keyWords) {
        List<Object> searchedTask = new ArrayList<>();
        int[] searchIndex = getSearchIndex(keyWords);
        for (int index : searchIndex) {
            if (index != -1 && index < mSearchObjs.size() * 2) {
                Object info = mSearchObjs.get(index / 2);
                if (info != null && !searchedTask.contains(info)) {
                    searchedTask.add(info);
                }
            }
        }
        return searchedTask;
    }

    /**
     * 找到匹配的索引數(shù)據(jù)
     *
     * @param keyWords
     *            搜索的關(guān)鍵字
     * @return 在初始化的索引數(shù)組的下標(biāo)數(shù)組
     */
    private int[] getSearchIndex(String keyWords) {
        Pattern pattern = Pattern.compile(keyWords, Pattern.CASE_INSENSITIVE | Pattern.LITERAL);
        Matcher matcher = pattern.matcher(mKeyWordString.toString());
        ArrayList<Integer> searchResult = new ArrayList<>();
        while (matcher.find()) {
            // 不宜在此處再做循環(huán),否則可能造成循環(huán)次數(shù)過多錯(cuò)誤
            searchResult.add(matcher.start());
        }
        int[] searchIndexes = new int[searchResult.size()];
        for (int i = 0; i < searchIndexes.length; i++) {
            int findIndex = findIndex(searchResult.get(i));
            searchIndexes[i] = (findIndex / 2) * 2;
        }
        return searchIndexes;
    }

    /**
     * 使用二分法找到指定字符位置在索引數(shù)組中的位置
     *
     * @param charAt
     *            字符在整個(gè)字符串中的位置
     * @return 在索引數(shù)組中的位置
     */
    private int findIndex(int charAt) {
        int low = 0;
        int high = mIndexes.length - 1;
        int mid = -1;
        while (low <= high) {
            mid = (low + high) >>> 1;
            int midVal = mIndexes[mid];
            if (midVal < charAt) {
                low = mid + 1;
            } else if (midVal > charAt) {
                high = mid - 1;
            } else {
                return mid;
            }
        }
        return mid;
    }

}

簡(jiǎn)單的使用和測(cè)試:

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("001", "小王", "天府大道一街"));
        students.add(new Student("002", "小王", "天府大道二街"));
        students.add(new Student("003", "小紅", "天府大道三街"));
        students.add(new Student("004", "小明", "天府大道四街"));
        students.add(new Student("005", "小王", "天府大道五街"));
        students.add(new Student("006", "小王", "軟件園南門"));
        students.add(new Student("007", "小張", "吉泰路"));
        try {
            FSearchTool tool = new FSearchTool(students, "name", "address");
            System.out.println(tool.searchTasks("明"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

輸出結(jié)果:

[Student [id=004, name=小明, address=天府大道四街]]

博客地址:對(duì)List對(duì)象列表屬性值的快速搜索

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,725評(píng)論 25 709
  • 自從確定學(xué)習(xí)方法:行動(dòng)->思考->規(guī)律->行動(dòng),我就開始執(zhí)行。 英語(yǔ),一直是我的短板,也是我的心結(jié),也是我的需要,...
    椰子數(shù)學(xué)閱讀 1,243評(píng)論 2 1
  • 2016年一月,昆明 陽(yáng)問我他能不能作我的男朋友,當(dāng)時(shí)我很靦腆的拒絕,理由是剛認(rèn)識(shí)沒多久,再說現(xiàn)在工作這么忙......
    祺涵空間閱讀 357評(píng)論 0 0

友情鏈接更多精彩內(nèi)容