搜索HashMap的Arraylist中的值

时间:2014-08-01 18:37:27

标签: android arraylist hashmap

我正在尝试搜索,跟踪hashmap的arraylist中的名称。我已搜索过很多网站,但无法获得任何解决方案。

以下是创建哈希映射的Arraylist的代码:

 ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
 searchText = (EditText) findViewById(R.id.searchText);

  //Count from the server
  int count = dataCount();

  for (int i = 0; i < dataCount; i++) 
    {
        HashMap<String, String> map = new HashMap<String, String>();

        // adding data to HashMap key => value
        map.put(KEY_ID, trackNumber);
        map.put(KEY_TITLE, trackTitle);
        map.put(KEY_ARTIST, trackArtist);
        map.put(KEY_DURATION, trackDuration);
        map.put(KEY_THUMB_URL, trackAlbumArt);

        // adding HashList to ArrayList
        songsList.add(map);

    }

    adapter=new LazyAdapter(this, songsList);        
    list.setAdapter(adapter);

在TextChanged上我试图获取搜索结果并使用新结果更新适配器。

我正在尝试用

中给出的类似逻辑

HashMap Searching For A Specific Value in Multiple Keys

Is it there a better way to Search HashMap from ArrayList

但无法获得任何结果。

谢谢!

1 个答案:

答案 0 :(得分:1)

选项1 :迭代列表项并搜索匹配项:

// this code wasn't tested - but I'm sure you'll get the idea
Map getSong(String title) {
    for(Map song : songsList) {
        if(song.get(KEY_TITLE).equals(title)) {
            return song;
        }
    }
    return Collections.emptyMap();
}

选项2 (首选):将歌曲保存到另一个地图(而不是列表)中,并将标题用作“关键字”:

Map<String, HashMap<String, String>> songsList = new HashMap<String, HashMap<String, String>>();

// add a song:
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, trackNumber);
map.put(KEY_TITLE, trackTitle);
map.put(KEY_ARTIST, trackArtist);
map.put(KEY_DURATION, trackDuration);
map.put(KEY_THUMB_URL, trackAlbumArt);
// adding HashList to Map
songsList.put(trackTitle, map);

然后您不必迭代列表来查找您的歌曲,只需执行以下操作:

Map getSong(String title) {
    return songsList.get(title);
}