TheDevMan
TheDevMan

Reputation: 5954

Search the values in Arraylist of HashMap

I am trying to search, track name from arraylist of hashmap. I have searched lots of sites on this, but couldn't get any solution.

Here is the code for creating Arraylist of hash maps:

 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);

On TextChanged I am trying to get the search results and update the adapter with new results.

I was trying out similar logic that was given in

HashMap Searching For A Specific Value in Multiple Keys

Is it there a better way to Search HashMap from ArrayList

But couldn't get any results.

Thanks!

Upvotes: 1

Views: 3606

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

Option 1: Iterate the list items and search for a match:

// 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();
}

Option 2 (preferred): save the songs into another Map (instead of a list) and use the title as the "key":

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);

then you don't have to iterate a list to find your song, but simply do:

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

Upvotes: 1

Related Questions