sara
sara

Reputation: 131

Search Hash Map array for specfic key android

I have an ArrayList of HashMap like this:

ArrayList<HashMap<String, String>> playListSongs = new ArrayList<HashMap<String, String>>();

I populate the list like this:

for (int i1 = 0; i1 < nl.getLength(); i1++) {
  // creating new HashMap
  HashMap<String, String> map = new HashMap<String, String>();
  Element e = (Element) nl.item(i1);
  // adding each child node to HashMap key => value
  map.put(KEY_SONGS, String.valueOf(i1));
  map.put(KEY_FILE, parser.getValue(e, KEY_FILE));
  map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
  map.put(KEY_FILE, parser.getValue(e, KEY_FILE));
  map.put(KEY_ALBUM, parser.getValue(e, KEY_ALBUM));
  map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
  map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
  map.put(KEY_ARTWORK, parser.getValue(e, KEY_ARTWORK));
  // Songs List of selected playlist
  playListSongs.add(map);
  // list view bind
  PopulateList(playListSongs);
}

Now i want to Get Album and songs of a specific Artist and song count from HashMap-array-list(playListSongs) to bind it to the list view.

How can I achieve this?

Upvotes: 2

Views: 4519

Answers (2)

Muhammad Nabeel Arif
Muhammad Nabeel Arif

Reputation: 19310

You can use this method to get songs of specific artist:

private ArrayList<String> getSongsByArtist(String artist){
    ArrayList<String> songs = new ArrayList<String>();
    for (HashMap<String, String> hashMap : playListSongs) {
        if(hashMap.get(KEY_ARTIST).equals(artist)){
            songs.add(hashMap.get(KEY_TITLE));
        }
    }
    return songs;       
}

To get distinct artists use following method:

private ArrayList<String> getDistinctArtists(){
    HashMap<String,String> duplicateTracker = new HashMap<String, String>();
    ArrayList<String> distinctArtists = new ArrayList<String>();
    for (HashMap<String, String> hashMap : playListSongs) {
        // Check whether artist is already added or not
        if(duplicateTracker.containsKey(hashMap.get(KEY_ARTIST))==false){
            //Add artist name to hash map
            duplicateTracker.put(hashMap.get(KEY_ARTIST), hashMap.get(KEY_ARTIST));
            distinctArtists.add(hashMap.get(KEY_ARTIST));
        }
    }
    return distinctArtists;     
}

Upvotes: 2

Rasel
Rasel

Reputation: 15477

Try like this

     for (int i1 = 0; i1 < playListSongs.size(); i1++) {
                    HashMap<String, String> map = playListSongs.get(i1);
String artist=map.get(KEY_ARTIST);                    
String songs=   map.get(KEY_SONGS);
String file=   map.get(KEY_FILE);
String duration=   map.get(KEY_DURATION);

SongDescription description=new SongDescription(artists,songs,file,duration);
desList.add(description);                     
if(artists.equals(desiredAtrist)){
songs----------->You need
}

}

Upvotes: 1

Related Questions