store values from text file into map
How do I read strings from a text file and store in a hashmap? File开发者_StackOverflow社区 contains two columns.
File is like:
FirstName LastName
Pranay Suyash and so on...Here's one way:
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
HashMap<String, String> map = new HashMap<String, String>();
while (scanner.hasNextLine()) {
String[] columns = scanner.nextLine().split(" ");
map.put(columns[0], columns[1]);
}
System.out.println(map);
}
}
Given input:
somekey somevalue
someotherkey someothervalue
this prints
{someotherkey=someothervalue, somekey=somevalue}
If your lines look differently, I either suggest you fetch columns[0]
and columns[1]
and do your string manipulation as needed, or, if you're comfortable with regular expressions, you could use Pattern
/ Matcher
to match the line against a pattern and get the content from the capture groups.
In the hash map if you want to map each row in the two columns you can make the first column value as the key and the second column as the value. But the keys should be unique in the Hashmap. If the first column values are unique you can go for the following approach
Map<String,String> map = new HashMap<String,String>();
map.put(firstColVal,secondColVal);
Just in case
- your keys (first column) don't contain spaces and
- your columns are separated by either a
:
, a=
or a white char (except newline)
then this may work:
Map<Object, Object> map = new Properties();
((Properties) map).load(new FileReader("inputfile.txt"));
Just saw your sample input... You shouldn't put that data in a map, unless it is guaranteed that all firstnames are unique.
Otherwise this will happen:
map.put("Homer", "Simpson"); // new key/value pair
map.put("Bart", "Simpson"); // new key/value pair
map.put("Homer", "Johnsson"); // value for "Homer" is replaced with "Johnsson"
System.out.println(map.get("Homer")); // guess what happens..
精彩评论