user1321824
user1321824

Reputation: 445

Object List to Hashmap

I have a list of type object as follows,

List<object> recordList

which will contain database record(integer,string) as follows,

[[1,AAAAAAAA],[2,BBBBBB]]

I need to split the data in the list and put into Hashmap<Integer,String> as follows,

I do knw how to split the data form the object list and poplualte the hashmap. How to populate the Hashmap with the data from list?

Upvotes: 0

Views: 1473

Answers (4)

Daniel
Daniel

Reputation: 971

package listHashMap;
import java.util.*;
public class MyList {
    public static void main(String [] args)
    {
        List<String> aList=new ArrayList<String>();
        Map<Integer,String> aMap = new HashMap<Integer, String>();
        aList.add("AAAA");
        aList.add("BBBB");
        for(int i=0;i<aList.size();i++){
            aMap.put(i+1,aList.get(i));
        }
        System.out.println(aMap.toString());

    }

}

Upvotes: 0

vels4j
vels4j

Reputation: 11298

if your List<object> containsObject[], you can do it like

HashMap<Integer,String> map  = new HashMap<Integer, String>();
for( Object obj : recordList) {
   Object[] objA = (String[]) obj ;
   map.put((Integer) objA[0],(String) objA[1]);
}

Upvotes: 0

sunleo
sunleo

Reputation: 10947

List<String> l = new ArrayList<String>();
Map<Integer,String> m = new HashMap<Integer, String>();
Iterator<String> ite = l.iterator();
while(ite.hasNext())
{
    String sTemp[] =ite.next().split(",");
    m.put(Integer.parseInt(sTemp[0]), sTemp[1]);
}

Upvotes: 1

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

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

   for (MyObject element : list) {
       if (element != null)
           map.put(element.getInt(), element.getString());
   }

Upvotes: 0

Related Questions