user2376600
user2376600

Reputation: 245

Hashmap inside a list to process my text file

I have a text file to be read and processed (separated by one tab space) which is something like:

GroupNum  Id   Name  Address
    1      1   john   USA
    1      2   mike   Uk
    2      3   smith  UK

How do i store each row in a map (userId being the key and the remaining being the values)and group in into a list and again map it as groupId with the key and the remaining as values?
Can anyone help me how to do this?

Upvotes: 0

Views: 150

Answers (2)

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

You can do this with help of meta data,

List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
int count = resultSet.getMetaData().getColumnCount();
while(resultSet.next()){
    HashMap<String,String> map = new HashMap<String,String>(); 
    for(int i=1;i<=count;i++){
        map.put(resultSet.getMetaData().getColumnName(i), resultSet.getString(resultSet.getMetaData().getColumnName(i)));
    }
    list.add(map);
}

A generic solution should work for any number of columns.

Upvotes: 0

NPKR
NPKR

Reputation: 5496

create Some Custom Object like GroupNum with properties (GroupNum, Id, Name, Address).

While reading ResultSet prepare

HashMap<String, GroupNum> hm;
while (rs.next) {

GroupNum  gn = new GroupNum ();
// set all values to GroupNum 

hm.put(gn.getGropuNum(), gn);

}

Upvotes: 1

Related Questions