I have some Java code like this :
Map<Map<String,String>,String> map = new HashMap<>();
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("properties.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
i++;
String[] parts = sCurrentLine.split(",");
System.out.println(parts[2]);
Map<String,String> tempMap = new HashMap<>();
tempMap.put("issuing_bank",parts[1]);
tempMap.put("card_switch",parts[2]);
tempMap.put("card_Type",parts[3]);
map.put(tempMap,parts[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
It looks strange that my map contains only first 12 elements that are stored from my text file. For debugging purpose I have used the variable i and print that out, which is printing the value of 22, which is the exact count in my text file.
My text file looks like this:
447747,ICCI,Visa,Credit
421323,ICCI,Visa,Debit
421630,ICCI,Visa,Debit
455451,ICCI,Visa,Debit
469375,ICCI,Visa,Debit
523951,ICCI,MasterCard,Credit
5399,ICCI,MasterCard,Debit
517652,HDFC,MasterCard,Credit
558818,HDFC,MasterCard,Credit
512622,SBI,MasterCard,Credit
526468,SBI,MasterCard,Credit
400975,Citi,Visa,Credit
402856,Citi,Visa,Credit
461726,Citi,Visa,Credit
552004,Citi,MasterCard,Debit
468805,Axis,Visa,Debit
418157,ICCI,Visa,Debit
524133,Citi,MasterCard,Credit
528945,HDFC,MasterCard,Credit
437748,SBI,MasterCard,Credit
524111,HDFC,MasterCard,Credit
431757,SBI,Visa,Credit
I’m very much confused, why only 12 elements are read into my map. Am I missing something here?
Thanks in advance.
The solution is simple: you have the wrong argument order in this line:
it should say
You must change the type parameters of your variable declaration accordingly. Where you have
you must put
Altogether, after these changes I believe you will have the structure you really want to have: a map from
parts[0]to the map of the rest of the record fields.I should add that your solution (in addition to your nick 🙂 gives you away as a developer who primarily codes in a dynamic language like Groovy; this style is not a good match for Java’s language features. In Java you’d be better off defining a specialized bean class:
First, this approach is nicer since your reading loop becomes simpler and more to the point:
Also this will allow you finer control over other aspects of your record; for example a nice custom
toStringand similar. Note also that this has hardly resulted in more code: it just got reorganized by the separation-of-concerns principle.(A minor observation at the end: in Java the s-prefix to String variables is not customary because it is redundant in statically-typed languages; rest assured that you will never encounter a bug in Java due to an Integer occuring where a String was expected.)