0

Can someone help me solve my problem, how to create List<Map<Integer, List<MyType>> in while cycle. I'm selecting data from database and I'd like to add objects, that accomplish select's where condition into List and then put it into Map<Integer, List<MyType> where map key is in my case integer from database column order_num. Finally I would like to add all created maps into List. Method's return value is List<Map<Integer, List<MyType>>>.

Here's my part of source:

while (cursor.moveToNext) {
       int id = cursor.getInt(cursor.getColumnIndex("item_id"));
       int orderNum = cursor.getInt(cursor.getColumnIndex("order_num"));
       String name = cursor.getString(cursor.getColumnIndex("item_name"));

       list.add(new Item(id, orderNum, name);
   }

now I'd like to add this list into Map where key is orderNum and value is List<Item>.

0

2 Answers 2

2

I'd declare an orderNum variable outside the loop so you can use it when the loop finishes:

int orderNum;
for ( cursor.moveToFirst; !cursor.isAfterLast(); cursor.moveToNext )
{
    int id = cursor.getInt( cursor.getColumnIndex( "item_id" ) );
    orderNum = cursor.getInt( cursor.getColumnIndex( "order_num" ) );
    String name = cursor.getString( cursor.getColumnIndex( "item_name" ) );

    list.add( new Item( id, orderNum, name ) );
}

map.put( orderNum, list );

I guess that whole block will be in some sort of loop too, so when that loop finishes then you can do

masterList.add( map );
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't you want to add to the map inside the loop? Otherwise you are only adding one data set to the map instead of each row from DB. Or did I misunderstand the question?
As I understood the question, the loop he has creates a list of data sets from the database query, then he wants to add that list to a map, each entry of which corresponds to one of his queries.
+1 for probably being right :) I wasn't sure which way the OP was wanting to do it so I made the suggestion just in case
0

Ty using a hashmap instead. I'm not sure if this work, but you can at least try it.

HashMap<Integer, ArrayList<MyClass>> myMap = new HashMap<Integer, ArrayList<MyClass>>();

Maybe this helps as well: http://www.roseindia.net/javatutorials/javahashmap.shtml

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.