Reputation: 137
I am trying to create a simple currency exchange program that reads from CSV file and exchange from one currency to another
these are data from my CSV file
Symbol, Currency, Dollar
USD,US Dollar,1
EUR,Euro,0.842850125
GBP,British Pound,0.761549464
INR,Indian Rupee,63.72054347
AUD,Australian Dollar,1.259237335
CAD,Canadian Dollar,1.257801755
.......
Here is my code
BufferedReader br = new BufferedReader(new FileReader("src/forex.csv"));
String line = null;
Map<String,Map<String, String>> outer = new HashMap<>();
Map<String, String> inner1 = new HashMap<>();
while((line = br.readLine())!=null){
String str[] = line.split(",");
inner1.put(str[1],str[2]);
outer.put(str[0],inner1);
}
System.out.println(outer);
Desired output like this
'USD': {'Currency': 'US Dollar', 'Dollar': '1'}, 'EUR': {'Currency': 'Euro', 'Dollar': '0.842850125'},
But I am now getting weird data which is way too long. I guess for each currency it's storing all the data from all the currencies and it is looping with no end.
Any idea how to fix it?
Upvotes: 0
Views: 189
Reputation: 18173
First of all you can not re-use inner1
because you will fill the same map over and over again. Also you're not putting the correct values into inner
compared to your desired output:
while ((line = br.readLine()) != null) {
String str[] = line.split(",");
String currencyCode = str[0];
Map<String, String> inner = new HashMap<>();
String currency = str[1];
inner.put('Currency', currency);
String xChangeRate = str[2];
inner.put('Dollar', xChangeRate);
outer.put(currencyCode, inner);
}
Upvotes: 1
Reputation: 6583
You put the same HashMap
inner1
into all outer
-Nodes. You could create a separate map for each entry like this:
BufferedReader br = new BufferedReader(new FileReader("src/forex.csv"));
String line = null;
Map<String,Map<String, String>> outer = new HashMap<>();
while((line = br.readLine())!=null){
String str[] = line.split(",");
Map<String, String> inner1 = new HashMap<>();
inner1.put(str[1],str[2]);
outer.put(str[0],inner1);
}
System.out.println(outer);
Upvotes: 1