简体   繁体   中英

Split the string of text file and store it in HashMap

I have a text file which has data as follows:

Surrender~abc~nov@2012
Surrender~bnc~bhdgvx
Surrender~nkhjb~bcdjh
.
.
.

I want to separate the data row by row and store second and third column values in Hashmap as 2nd -> key and 3rd -> value and check if the value entered by user exist in the Hashmap and return true.

I tried following but getting java.lang.ArrayIndexOutOfBoundsException: 3 ..Please guide.

HashMap hm = new HashMap();
FileInputStream fstream = new FileInputStream("Surrender.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;
while ((strLine = br.readLine()) != null)   {
    String[] parts = strLine.split("~");
    for (int i = 0; i <= parts.length; i++) {
       if(!parts[i].equalsIgnoreCase("Surrender")){
    String key=parts[i];
    String value=parts[i++];
    if(key!=null && value!=null)
    hm.put(key,value);
}
    }
}

System.out.println("HashMap size..." + hm.size());
in.close();

Since each of your lines looks like this:

Surrender~abc~nov@2012

there are three parts after splitting by ~ :

  • Surrender
  • abc
  • nov@2012

These parts are numberd from 0 to 2 .

Solution: Don't loop over the parts . Do this instead:

hm.put(parts[1], parts[2]);

Drop these lines:

for (int i=0;i<=parts.length;i++) {
    if (!parts[i].equalsIgnoreCase("Surrender")) {
        hm.put(parts[i], parts[++i]);
    }
}

Note: Use a generic Map :

Map<String, String> hm = new HashMap<>(); // Java 7

Replace this:

for (int i = 0; i <= parts.length; i++) {
    if (!parts[i].equalsIgnoreCase("Surrender")) {
        hm.put(parts[i], parts[++i]);
    }
}

with

if (parts.length > 2 && !parts[0].equalsIgnoreCase("Surrender")) {
    hm.put(parts[1], parts[2]);
}

If The data provided in the question is always three parts long you can skip parts.length > 2

First, please use types on your HashMap...

HashMap<String, String> hm = new HashMap<String, String>();

Second, why loop through the split array if its fixed size? I also believe you create problems for yourself when you access an element with [++i], which increments your counter. On the last iteration of the loop through the split, this may put it out of bounds.

Try something like:

if (parts[0].equalsIgnoreCase("Surrender")) {
    hm.put(parts[1], parts[2]);
}

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