Is it there a better way to Search HashMap from ArrayList

霸气de小男生 提交于 2020-01-07 04:12:09

问题


I am trying to implement Searching in ListView. My ListView is comprised of HashMap in ArrayList and I managed to implement the logic but I guess there is much object and memory allocation in my approach each time the text change. Therefore I am looking for less memory allocated logic to search in my ListView with HashMap in ArrayList

@Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            //textlength = searchBar.getText().length();
            //text_sort.clear();
            sortedArrayList.clear();


            for (int i = 0; i < myHistList.size(); i++) {

                HashMap<String, String> hash = new HashMap<String, String>(); 
                hash = myHistList.get(i);

                if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1) {

                    String callerNum1 = hash.get("myNumber");
                    String myName1 = hash.get("myName");


                    HashMap<String, String> searchedHash = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    searchedHash.put("myNumber", callerNum1);
                    searchedHash.put("myName", myName1);
                    recordingFile1);

                    // adding HashList to ArrayList
                    sortedArrayList.add(searchedHash);

                }
            }

            ListView actualLv = mPullRefreshListView.getRefreshableView();
            actualLv.setAdapter(new myHistoryListAdapter(myHistory.this, sortedArrayList));

        }

回答1:


At first you can replace

HashMap<String, String> hash = new HashMap<String, String>(); 
hash = myHistList.get(i);

with just

 HashMap<String, String> hash = myHistList.get(i);

It will slightly reduce the number of redundant objects.

At second step if you need to compare strings are the same but ignore letters' case you can try to simplify your if condition

if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1)

with

if(hash.get("myName").compareToIgnoreCase(searchBar.getText().toString()) == 0)

Also if you put the String callerNum1 = hash.get("myNumber"); above the if statement then you can save some time because you don't need to look through your HashSet two times to search the same element. It will look like following:

String callerNum1 = hash.get("myNumber");

if(callerNum1.compareToIgnoreCase(searchBar.getText().toString()) == 0){
     ...
}


来源:https://stackoverflow.com/questions/19951854/is-it-there-a-better-way-to-search-hashmap-from-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!