简体   繁体   中英

Read file into HashMap Java

I'm trying to read lines from file into Arraylist. Here is my writer :

private Map<Integer, ArrayList<Integer>> motPage = 
                                             new HashMap<Integer, ArrayList<Integer>>();

private void writer() throws UnsupportedEncodingException, FileNotFoundException, IOException{

  try (Writer writer = new BufferedWriter(
                          new OutputStreamWriter(
                             new FileOutputStream("/home/kdiri/workJuno/motorRecherche/src/kemal.txt"), "utf-8"))) {
    for(Map.Entry<Integer, ArrayList<Integer>> entry : motPage.entrySet()){
      writer.write(entry.getKey() + " : " + entry.getValue() + "\n");
    }
  }
}

And this is an exemple result in the file kemal.txt :

0 : [38, 38, 38, 38, 199, 199, 199, 199, 3004, 3004, 3004, 3004, 23, 23]

My question is how can I read it these lines efficiently into Hashmap again ? Because size of file is about 500MB. Thank you in advance.

As JonSkeet said, you should start with something working. Find below one possible way. The snippet is kept quite verbose to show the principle.

String line = "0 : [38, 38, 38, 38, 199, 199, 199, 199, 3004, 3004, 3004, 3004, 
    23, 23]";

int firstSpace = line.indexOf(" ");
int leftSquareBracket = line.indexOf("[");
int rightSquareBracket = line.indexOf("]");

String keyString = line.substring(0, firstSpace);        
String[] valuesString = line.substring(leftSquareBracket + 1, rightSquareBracket)
    .split(", ");

int key = new Integer(keyString);
List<Integer> values = new ArrayList<>(valuesString.length);
for (String value : valuesString) {
    values.add(new Integer(value));
}

Map<Integer, List<Integer>> motPage = new HashMap<>();
motPage.put(key, values);

Btw. read ... these lines efficiently into Hashmap depends on your requirements. Efficiency could be for example:

  • read speed of the huge file
  • convertion speed String to Integer
  • small size of the bytecode
  • less object generation
  • ... there could be other as well

When the snippet does not fulfil your efficiency criteria. Start to tune the part which impacts your criteria.

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