DolDurma
DolDurma

Reputation: 17289

Java retrieve returned ArrayList to HashMap

In my simple java application i have this function to return ArrayList:

Items.java class:

package com.example.Hadis;

/**
 * Created by tux-world on 8/1/14.
 */
public class Items {

    public int id;
    public String content;
}

ArrayList function for fill and return result:

DataBaseHelper.java class's getFavorite function :

public ArrayList<Items> getFavorite(){
    ArrayList<Items> arrayList = new ArrayList<Items>();

    do {

        Items dbItems = new Items();

        dbItems.id = cursor.getInt(0);
        dbItems.content = cursor.getString(1);
        arrayList.add(dbItems);
    } while (cursor.moveToNext());

    return arrayList;
}

i want to fetch this return ArrayList and fill HashMap but i can not program this part of project

Defined map as Method in class:

    static Map<Integer,String> map = new HashMap<Integer,String>();

retrive ArrayList and my problem is this:

    DatabaseHandler db = new DatabaseHandler(ApplicationHadith.this);
    ArrayList<Items> list = db.getFavorite();

    Iterator<Items> it = list.iterator();
    while(it.hasNext())
    {

      // map.put( it.id , it.content )

    }

how to retrive getFavorite() and fill HashMap? please help me.Thanks

Upvotes: 1

Views: 78

Answers (3)

user3487063
user3487063

Reputation: 3682

while(it.hasNext())
    {
Item item = (Item) it.next();

       map.put( item.getId() , item.getContent() )

    }

Have getters generated for id and content

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272237

Just use a simple for loop e.g.

for (Item item : list) {
   map.put( item.id, item.content);
}

I wouldn't normally use an Iterator in this scenario. The enhanced for-loop syntax above dates from Java 5.

Upvotes: 4

Eran
Eran

Reputation: 393781

You need to use the iterator's next() method to get the instance of Items :

Iterator<Items> it = list.iterator();
while(it.hasNext())
{
  Items item = it.next();
  map.put( item.getID() , item );

}

Upvotes: 1

Related Questions