Reputation: 21
I have to read a file. File is as below -
I have written below code wherein I read that file into hashtable.
public Hashtable<String, String> readDataFromFile(String fileName) {
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String strLine = null;
String []prop = null;
while((strLine = br.readLine()) != null) {
prop = strLine.split("\t");
recruiters.put(prop[0], prop[1]);
}
br.close();
fr.close();
}catch(Exception exception) {
System.out.println("Unable to read data from recruiter file: " + exception.getMessage());
}
return recruiters;
}
This function returns a hashtable with first argument as id and second as the link
Now, I want to write a function in which I can read the hashtable and also append the second argument to first and that function should return a total url as result..
something like www.abc.com/123
This is how I started but its not working for me.. Plesae suggest improvement.
public String readFromHashtable(Hashtable recruiters){
String url=null;
Set<String> keys = hm.keySet();
for(String key: keys){
//Reading value and key
// Appending id into url and returning each of the url.
}
return url;
}
Upvotes: 1
Views: 904
Reputation: 4696
If you want both values (key + value), it's easiest to iterate over the entries
with .entrySet()
.
You need to somehow collect your URLs. In your current code, you reassign the url
variable every time the loop repeats, so in the end, you only return the last url.
Something like this should work:
public List<String> readFromHashtable(Hashtable recruiters){
List<String> urls = new ArrayList<String>(recruiters.size());
for(Entry e : recruiters.entrySet()){
urls.add(e.getValue() + '/' + e.getKey());
}
return urls;
}
Also, why are you using HashTable instead of HashMap? The main difference is that HashTable is synchronized (used for threaded applications) and HashMap is not. If you are not using threads to operate on the HashTable, you might prefer HashMap.
Upvotes: 1