对模糊搜索HashMap继续改进

直接迭代KeySet即可,速率提升一倍,MyLikeHashMap查找9992大致运行时间32,MyLikeHashMap_1大致时间为15

package cn.xbmu.lib.jfly.test;

import java.util.*;

/**
 * 模糊搜索HashMap
 * @param <K>
 * @param <V>
 * @author JFly
 */
public class MyLikeHashMap_1<K, V> extends HashMap<K, V> {

    public List<V> get(String key, boolean like) {
        List<V> list = null;
        if (like) {
            list = new ArrayList<V>();
            K[] a = null;
            Set<K> set = this.keySet();
            //a = (K[])set.toArray();
            Iterator<K> it = set.iterator();
            boolean more = it.hasNext();
            K elem = null;
            while(it.hasNext()) {
                elem = it.next();
                if(elem.toString().indexOf(key) == -1) {
                    continue;
                } else {
                    list.add(this.get(elem));
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        MyLikeHashMap_1<String, String> mh = new MyLikeHashMap_1<String, String>();
        for (int i = 0; i < 100000; i++) {
            mh.put("A_" + i, "AAAAAA" + i);
        }
        long time = System.currentTimeMillis();
        System.out.println(mh.get("9992", true));
        System.out.println(System.currentTimeMillis() - time);
    }
}

 

你可能感兴趣的:(HashMap)