Skip to content

Read Text File into HashMap in Java Example

This example shows how to read a text file into HashMap in Java. This example uses a text file containing keys and values and converts them to the HashMap object.

How to read a text file to HashMap in Java?

I am going to use the below given text file contents for the purpose of this example.

The text file contains a person’s name and age separated by a colon “:” in each line. The name will be used as a key of the HashMap object and age will be the value.

I have saved the text file at “E:\text-values.txt” location. Please change the code as per the location of your text file.

I am going to use the BufferedReader to read the text file line by line, split the line by colon and put the parts in the HashMap as given below.

Output

Important Note:

As you can see from the output, the order of the HashMap entries is not the same as file lines. That is because the HashMap class does not guarantee to maintain the insertion order of the mappings.

If the order of lines is important to you, use the LinkedHashMap class instead of the HashMap class. Change the below line in the code.

Replace it with the line given below.

Also, do not forget to import the LinkedHashMap class. After these changes, the output will have the map entries in the same order as the file lines.

Output

If you want to write HashMap to file, please refer to how to write HashMap to a text file example.

This example is a part of the Java HashMap tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.