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.


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.


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



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping