简体   繁体   中英

Split a text file using delimiter \t and store in hashmap in java

I have a text file of n columns and n rows separated by tab space.. How do i use split function to store the columns and rows into a hashmap.Please help.
My text file will be like..

Dept Id Name Contact
IT 1 zzz 678

ECE 2 ttt 789

IT 3 rrr 908

I tried the following.But it dint work.

Map<String,String> map=new HashMap<String,String>();
while(lineReader!=null)
{
String[] tokens = lineReader.split("\\t");
key = tokens[0];
values = tokens[1];
map.put(key , values );
System.out.println("ID:"+map.get(key ));
System.out.println("Other Column Values:"+map.get(values ));
}

This returns the key of the last entry(row) of the file and value as null. But i need to store all rows and columns in the map. How do i do it?

If I understand your data correctly,

After

String[] tokens = lineReader.split("\\t");

is processed on the first line, you'd have 4 tokens in the array.

I think you are using wrong logic, if you want to store the map in the following way:

IT -> (1 ZZZ 678) .... etc then you need to process the data differently.

What you are storing in the map is follows: IT -> 1 ECE -> 2 ... and so on.

That's why you get null when you are trying to do:

map.get(value);

What you should instead print is the Key and map.get(key) .

Actually, in any case I don't think Map is what you want (but I don't know what you really want).

For now though, for your understanding of this problem try printing:

System.out.println("Total collumns: "+ tokens.length);

Updated:

This should work for you. It isn't the most elegant implementation for what you want, but gets the job done. You should try improving it from here on.

Map<String,String> map=new HashMap<String,String>();
while(lineReader!=null)
{
String[] tokens = lineReader.split("\\t");
key = tokens[1];
values = tokens[2]+tokens[3];
map.put(key , values );
System.out.println("ID:"+key);
System.out.println("Other Column Values:"+map.get(key));
}

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM