My map will be:
{"hashMapList":[{"aGasConsum":1,"invAmt":54.0,"invNo":"222222222","custCode":"11111111111111",
"customer":{
{"cusName": "abc"},
{"billAddr":"qqq"},
{"area":
{"areName":"xyz"},
{"id":2}
}
},
{"aGasConsum":2,"invAmt":55.0,"invNo":"222222222","custCode":"11111111111111",
"customer":{
{"cusName": "abc"},
{"billAddr":"qqq"},
{"area":
{"areName":"xyz"},
{"id":2}
}
}]}
But current situation is: when it got the same key it overlap the value and put like.
{"hashMapList":[{"aGasConsum":1,"invAmt":54.0,"invNo":"222222222","custCode":"11111111111111",
"customer":{"area":{"id":2}}},
{"aGasConsum":2,"invAmt":55.0,"invNo":"222222222","custCode":"11111111111111",
"customer":{"area":{"id":2}}}]}
My tried code:
public List<HashMap> displayHashMap(List<Tuple> tupleList, HashMap container) {
HashMap map = new HashMap();
List<HashMap> listHash = new ArrayList<HashMap>();
Map<String, List<HashMap>> exist = new HashMap<String, List<HashMap>>();
List<HashMap> existMap = new ArrayList<HashMap>();
for (int i = 0; i < tupleList.size(); i++) {
for (String t : (List<String>) container.get("columns")) {
if (t.indexOf('.', t.indexOf('.') + 1) != -1) {
String[] parts = t.split("\\.");
HashMap m1 = new HashMap();
m1.put(parts[2], tupleList.get(i).get(parts[2]));
HashMap m2 = new HashMap();
m2.put(parts[1], m1);
map.put(parts[0], m2);
//existMap.add(m1);
existMap.add(m2);
exist.put(parts[0], existMap);
} else if (t.contains(".")) {
String[] parts = t.split("\\.");
HashMap m3 = new HashMap();
m3.put(parts[1], tupleList.get(i).get(parts[1]));
map.put(parts[0], m3);
existMap.add(m3);
exist.put(parts[0], existMap);
} else {
map.put(t, tupleList.get(i).get(t));
}
}
listHash.add(map);
map = new HashMap();
}
System.err.println("final: " + existMap);
System.err.println("final: " + exist);
return listHash;
}
I am confused how to handle this loop and make a nested hashmap.
public List<HashMap> displayHashMap(List<Tuple> tupleList, HashMap container) {
HashMap map = new HashMap();
List<HashMap> listHash = new ArrayList<HashMap>();
HashMap existMap = new HashMap();
HashMap existMap1 = new HashMap();
List<HashMap> existMapList = new ArrayList<HashMap>();
for (int i = 0; i < tupleList.size(); i++) {
for (String t : (List<String>) container.get("columns")) {
if (t.indexOf('.', t.indexOf('.') + 1) != -1) {
String[] parts = t.split("\\.");
existMap1.put(parts[2], tupleList.get(i).get(parts[2]));
if (!existMap.containsKey(parts[1])) {
existMap.put(parts[1], existMap1);
}
existMapList.add(existMap);
if (map.containsKey(parts[0])) {
map.put(parts[0], existMapList);
}
} else if (t.contains(".")) {
String[] parts = t.split("\\.");
existMap.put(parts[1], tupleList.get(i).get(parts[1]));
map.put(parts[0], existMap);
} else {
map.put(t, tupleList.get(i).get(t));
}
existMapList = new ArrayList<HashMap>();
}
existMapList = new ArrayList<HashMap>();
listHash.add(map);
existMap = new HashMap();
existMap1 = new HashMap();
map = new HashMap();
}
return listHash;
}
Done!!
Related
I am trying to automate an application. For that, i am using hash map for excel data set and i have created my methods for performing action on that data.
Class file to execute is shown below
#Test
public void testLAP_Creamix() throws Exception {
try {
launchMainApplication();
Lapeyre_frMain Lapeyre_frMainPage = new Lapeyre_frMain(tool, test, user, application);
HashMap<String, ArrayList<String>> win = CreamixWindowsDataset.main();
SortedSet<String> keys = new TreeSet<>(win.keySet());
for (String i : keys) {
System.out.println("########### Test = " + win.get(i).get(0) + " ###########");
Lapeyre_frMainPage.EnterTaille(win.get(i).get(1));
Lapeyre_frMainPage.SelectCONFIGURATION(win.get(i).get(2));
Lapeyre_frMainPage.SelectPLANVASQUE(win.get(i).get(3));
Lapeyre_frMainPage.SelectCOULEUR(win.get(i).get(4));
Lapeyre_frMainPage.SelectPOIGNEES(win.get(i).get(5));
Lapeyre_frMainPage.SelectTYPE_DE_MEUBLE(win.get(i).get(6));
Lapeyre_frMainPage.VerifyPanierPrice(win.get(i).get(7));
Lapeyre_frMainPage.VerifyECO_PARTPrice(win.get(i).get(8));
Lapeyre_frMainPage.ClickCREAMIXReinit();
System.out.println("########### Test End ##############");
}
test.setResult("pass");
} catch (AlreadyRunException e) {
} catch (Exception e) {
verificationErrors.append(e.getMessage());
throw e;
}
}
Hash Map code :
public static HashMap<String, ArrayList<String>> main() throws IOException {
final String DatasetSheet = "src/test/resources/CreamixDataSet.xlsx";
final String DatasetTab = "Creamix";
Object[][] ab = DataLoader.ReadMyExcelData(DatasetSheet, DatasetTab);
int rowcount = DataLoader.myrowCount(DatasetSheet, DatasetTab);
int colcount = DataLoader.mycolCount(DatasetSheet, DatasetTab);
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
// i = 2 to avoid column names
for (int i = 2; i < rowcount;) {
ArrayList<String> mycolvalueslist = new ArrayList<String>();
for (int j = 0; j < colcount;) {
mycolvalueslist.add(ab[i][j].toString());
j++;
}
map.put(ab[i][0].toString(), mycolvalueslist);
i++;
}
return map;
}
Query: I was able to run this code few days back, but now after adding some new columns it is giving me below mentioned error.
IndexOutOfBoundsException Index 7 out of bounds for length 7
I am not able to trace the issue here, what should i look for? please help!
for (String i : keys) {
arr = win.get(i);//debug here,watch it size
Lapeyre_frMainPage.EnterTaille(arr.get(1));
}
I want to retrieve some rows of a 2d array.
example: I have file named as "data.csv", which contains
age sex zipcode classtype
21 m 23423 1
12 f 23133 2
23 m 32323 2
23 f 23211 1
The below mentioned code will give output like this:
{age=[21,12,23,23],sex=[m,f,m,f],zipcode=[23423,23133,32323,23211],classtype=[1,2,2,1]}
Now I want to retrieve rows which have classtype 1 and store this values in a new 2d array.
like partition1={{21,m,23423,1},{23,f,23211,1}}
public class CsvParser {
public static void main(String[] args) {
try {
FileReader fr = new FileReader((args.length > 0) ? args[0] : "data.csv");
Map<String, List<String>> values = parseCsv(fr, " ", true);
System.out.println(values);
List<List<String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
List<String> data = new ArrayList<>(25);
data.add(values.get("age").get(row));
data.add(values.get("sex").get(row));
data.add(values.get("zipcode").get(row));
data.add(values.get("classtype").get(row));
partition1.add(data);
}
}
System.out.println(partition1);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, List<String>> parseCsv(Reader reader, String separator, boolean hasHeader) throws IOException {
Map<String, List<String>> values = new LinkedHashMap<String, List<String>>();
List<String> columnNames = new LinkedList<String>();
BufferedReader br = null;
br = new BufferedReader(reader);
String line;
int numLines = 0;
while ((line = br.readLine()) != null) {
if (StringUtils.isNotBlank(line)) {
if (!line.startsWith("#")) {
String[] tokens = line.split(separator);
if (tokens != null) {
for (int i = 0; i < tokens.length; ++i) {
if (numLines == 0) {
columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
} else {
List<String> column = values.get(columnNames.get(i));
if (column == null) {
column = new LinkedList<String>();
}
column.add(tokens[i]);
values.put(columnNames.get(i), column);
}
}
}
++numLines;
}
}
}
return values;
}
}
FileReader file1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(file1);
String line = "";
while ((line = buffer.readLine()) != null) {
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
if(str[0]!=null||str[1]!=null||str[2]!=null){
sb.append("'" + str[0] + "',");
sb.append("'" +str[1] + "',");
sb.append("'" +str[2] + "'");
}
CSV File Must to be split comma based it should be work
Once I changed Map<String, List<String>> values = parseCsv(fr, "\\s,", true); to Map<String, List<String>> values = parseCsv(fr, " ", true); I was able to get the data in the right format...
From there it was just a matter to read through each row of classtype, when I found a value that matched 1, I would pull out each property for the given row and add it to a List, forming a single row. This was then added to another List which would maintain all the matching rows, for example...
List<List<String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
List<String> data = new ArrayList<>(25);
data.add(values.get("age").get(row));
data.add(values.get("sex").get(row));
data.add(values.get("zipcode").get(row));
data.add(values.get("classtype").get(row));
partition1.add(data);
}
}
System.out.println(partition1);
Which outputs...
[[21, m, 23423, 1], [23, f, 23211, 1]]
If you're looking for a more automated method, then I'm afraid you're out of luck, as Map makes no guarantee about the order that the keys are stored, iterated.
Of course, instead of using a List<List>, you could use a List<Map> which would maintain the keys for each value, for example...
List<Map<String, String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
Map<String, String> data = new HashMap<>(25);
for (String key : values.keySet()) {
data.put(key, values.get(key).get(row));
}
partition1.add(data);
}
}
System.out.println(partition1);
Which outputs...
[{sex=m, classtype=1, zipcode=23423, age=21}, {sex=f, classtype=1, zipcode=23211, age=23}]
I have a ArrayList<HashMap<String,String>> that I am using the toString() method on to store in a database.
Here is the code that I use to store it the toString() to a database (it works):
HashMap<String, String> commentsHash = null;
ArrayList<HashMap<String, String>> test2 = new ArrayList<HashMap<String, String>>();
for (int i=0; i < test.size(); i++)
{
String timestamp = test.get(i).get("timestamp");
String last_name = test.get(i).get("last_name");
String first_name = test.get(i).get("first_name");
String comment = test.get(i).get("comment");
commentsHash = new HashMap<String, String>();
commentsHash.put("creation_timestamp", timestamp);
commentsHash.put("first_name", first_name);
commentsHash.put("last_name", last_name);
commentsHash.put("comment", comment);
test2.add(commentsHash);
}
dbHelper.addCommentsToMyLiPost(Integer.parseInt(sqlId), test2.toString());
Here is the method I want to use to convert a string to a HashMap<String, String>:
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
I have tried using .split(",") on the string to split the string into 2 parts, but instead of returning two, it returns 8.
Here is what the toString() method prints. It is an ArrayList of HashMaps, and I am trying to grab the two HashMaps that are inside of the ArrayList.
[{comment=hello, last_name=u1, first_name=u1, creation_timestamp=1404938643772}, {comment=hello2, last_name=u2, first_name=u2, creation_timestamp=1404963221598}]
In convertToStringToHashMap, when you put your data into HashMap, the old value will be replaced since they have same key for each records, such as comment, last_name, etc.
public static Map<String, Map<String, String>> convertToStringToHashMap(String text)
{
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
Map<String, String> data = new HashMap<String, String>();
int gap = 8;
int key = 1;
for (int i = 1; i + 2 <= split.length; i += 2)
{
data.put(split[i], split[i+1]);
if((i + 1) % gap == 0)
{
map.put(String.valueOf(key++), data);
data = new HashMap<String, String>();
data.clear();
}
}
return map;
}
This will return a Map:
2={first_name=u2, last_name=u2, comment=hello2, creation_timestamp=1404963221598}
1={first_name=u1, last_name=u1, comment=hello, creation_timestamp=1404938643772}
This program will recreate the whole list from the database entry
Pattern firstPat = Pattern.compile("\\{.*?\\}");
Matcher firstMat = firstPat.matcher(text);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while(firstMat.find()){
HashMap<String, String> map = new HashMap<>();
String assignStrings = firstMat.group();
String [] assignGroups = assignStrings.substring(1,assignStrings.length()-1).split("\\s*\\,\\s*");
for(String assign:assignGroups){
String [] parts = assign.split("\\=");
map.put(parts[0], parts[1]);
}
list.add(map);
}
return list
i have data fetched from my webservice in
ArrayList<HashMap<String,String>>
Now i want to convert each object of the above to
String[]
how do i do this?
any help would be much appreciated!
try
ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
HashMap<String, String> n = new HashMap<String, String>();
n.put("a", "a");
n.put("b", "b");
test.add(n);
HashMap<String, String> m = test.get(0);//it will get the first HashMap Stored in array list
String strArr[] = new String[m.size()];
int i = 0;
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
strArr[i] = current;
i++;
}
}
The uses for an Hashmap should be an Index of HashValues for finding the values much faster. I don't know why you have Key and Values as Strings but if you only need the values you can do it like that:
ArrayList<HashMap<String, String>> test = new ArrayList<>();
String sum = "";
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
sum = sum + current + "<#>";
}
}
String[] arr = sum.split("<#>");
It's not a nice way but the request isn't it too ;)
ArrayList<HashMap<String, String>> meterList = controller.getMeter();
HashMap<String, String> mtiti = meterList.get(0);//it will get the first HashMap Stored in array list
String[] strMeter = new String[mtiti.size()];
String meter = "";
for (HashMap<String, String> hash : meterList) {
for (String current : hash.values()) {
meter = meter + current + "<#>";
}
}
String[] arr = meter.split("<#>");
I have 3 vector as given below.Here Vector1, Vector2, Vector3 will not be of same size.below given is an ideal situation that will occur some time only.It might be possible that vector2 only contain one extra {} with d=3,... and vector1 and Vector3 will don't have that(d=3) entry.
Vector1 := [{a=Prity, b=Joshi, c=Pyarelal, d=1},{a=tiny, b=darji, c=Mohandas, d=2}]
Vector2 := [{e=age-29, f=height-5, d=1},{e=age-52, f=height-6, d=2}]
Vector3 := [{g=pet-dog, d=1},{g=pet-cat, d=2}]
I want a vector that will merge values and give me final vector as displayed below
Vector4 := [{a=Prity, b=Joshi, c=Pyarelal, d=1,e=age-29, f=height-5, g=pet-dog}, {a=tiny, b=darji, c=Mohandas, d=2, e=age-52, f=height-6, g=pet-cat}]
I implemented one logic but it is time consuming.Does anyone has better option ?????
int columnSize = Vector1.size() > Vector2.size() ? Vector1.size()
: Vector2.size();
Hashtable finalHash[] = new Hashtable[columnSize];
for (i = 0; i < Vector1.size(); i++) {
finalHash[i] = (Hashtable) Vector1.elementAt(i);
for (int z = 0; z < Vector2.size(); z++) {
Hashtable hashtwo = (Hashtable) Vector2.elementAt(z);
if (hashtwo.containsValue(finalHash[i]
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashtwo);
Vector2.removeElementAt(z);
}
}
for (int z = 0; z < Vector3.size(); z++) {
Hashtable hashduerenew = (Hashtable) Vector3.elementAt(z);
if (hashduerenew.containsValue(finalHash[i]
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashduerenew);
Vector3.removeElementAt(z);
}
}
}
columnSize = Vector2.size() > Vector3.size() ? Vector2.size() : Vector3
.size();
Hashtable finalHashtable = new Hashtable();
for (int t = 0; t < Vector2.size(); t++, i++) {
finalHashtable = (Hashtable) Vector2.elementAt(t);
for (int z = 0; z < Vector3.size(); z++) {
Hashtable hashtwo = (Hashtable) Vector3.elementAt(z);
if (hashtwo.containsValue(finalHashtable
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashtwo);
Vector3.removeElementAt(z);
break;
}
}
finalHash[i].putAll(finalHashtable);
Vector2.removeElementAt(t);
}
int t = 0;
while (t < Vector3.size()) {
finalHash[i] = (Hashtable) Vector3.elementAt(t);
t++;
i++;
}
I think he wanted something like this:
private static Vector<Hashtable<Character, String>> vector1;
private static Vector<Hashtable<Character, String>> vector2;
private static Vector<Hashtable<Character, String>> vector3;
public static void main(final String[] args) {
setUp();
// Your final vector
Vector<Hashtable<Character, String>> mergedVector = new Vector<Hashtable<Character, String>>();
// Considering every vector has the same size
addToMerged(mergedVector, vector1);
addToMerged(mergedVector, vector2);
addToMerged(mergedVector, vector3);
// Print the result
for (Hashtable<Character, String> hash : mergedVector) {
for (Entry<Character, String> set : hash.entrySet()) {
System.out.println("KEY: " + set.getKey() + ", VALUE: "
+ set.getValue());
}
System.out.println("\nNext hashtable.\n");
}
}
private static void setUp() {
vector1 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash11 = new Hashtable<Character, String>();
hash11.put('a', "Prity");
hash11.put('b', "Joshi");
hash11.put('c', "Pyarelal");
hash11.put('d', "1");
vector1.add(hash11);
Hashtable<Character, String> hash12 = new Hashtable<Character, String>();
hash12.put('a', "tiny");
hash12.put('b', "darji");
hash12.put('c', "Mohandas");
hash12.put('d', "2");
vector1.add(hash12);
vector2 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash21 = new Hashtable<Character, String>();
hash21.put('e', "age-29");
hash21.put('f', "height-5");
hash21.put('d', "1");
vector2.add(hash21);
Hashtable<Character, String> hash22 = new Hashtable<Character, String>();
hash22.put('e', "age-52");
hash22.put('f', "height-6");
hash22.put('d', "2");
vector2.add(hash22);
vector3 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash31 = new Hashtable<Character, String>();
hash31.put('g', "pet-dog");
hash31.put('d', "1");
vector3.add(hash31);
Hashtable<Character, String> hash32 = new Hashtable<Character, String>();
hash32.put('g', "pet-cat");
hash32.put('d', "2");
vector3.add(hash32);
}
private static void addToMerged(
final Vector<Hashtable<Character, String>> mergedVector,
final Vector<Hashtable<Character, String>> vector) {
for (int i = 0; i < vector.size(); i++) {
Hashtable<Character, String> hashtable = vector.get(i);
for (Entry<Character, String> entrySet : hashtable.entrySet()) {
boolean added = false;
for (int j = 0; j < mergedVector.size() && !added; j++) {
Hashtable<Character, String> hashtable2 = mergedVector
.get(j);
if (!hashtable2.containsKey(entrySet.getKey())) {
hashtable2.put(entrySet.getKey(), entrySet.getValue());
added = true;
break;
} else if (hashtable2.get(entrySet.getKey()).equals(
entrySet.getValue())) {
added = true;
break;
}
}
if (!added) {
Hashtable<Character, String> hashtable2 = new Hashtable<>();
hashtable2.put(entrySet.getKey(), entrySet.getValue());
mergedVector.add(hashtable2);
}
}
}
}
Hashtable doesn't keep the order in which you add the elements, so your vectors originally aren't going to look as you wrote them in your post, if you want to archieve that you will have to use LinkedHashTable.
Taking into account the comment before, you can merge your vectors like this:
public static void main(String[] args) {
Vector<Hashtable<Character, String>> vector1 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash11 = new Hashtable<Character, String>();
hash11.put('a', "Prity");
hash11.put('b', "Joshi");
hash11.put('c', "Pyarelal");
hash11.put('d', "1");
vector1.add(hash11);
Hashtable<Character, String> hash12 = new Hashtable<Character, String>();
hash12.put('a', "tiny");
hash12.put('b', "darji");
hash12.put('c', "Mohandas");
hash12.put('d', "2");
vector1.add(hash12);
Vector<Hashtable<Character, String>> vector2 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash21 = new Hashtable<Character, String>();
hash21.put('e', "age-29");
hash21.put('f', "height-5");
hash21.put('d', "1");
vector2.add(hash21);
Hashtable<Character, String> hash22 = new Hashtable<Character, String>();
hash22.put('e', "age-52");
hash22.put('f', "height-6");
hash22.put('d', "2");
vector2.add(hash22);
Vector<Hashtable<Character, String>> vector3 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash31 = new Hashtable<Character, String>();
hash31.put('g', "pet-dog");
hash31.put('d', "1");
vector3.add(hash31);
Hashtable<Character, String> hash32 = new Hashtable<Character, String>();
hash32.put('g', "pet-cat");
hash32.put('d', "2");
vector3.add(hash32);
// Your final vector
Vector<Hashtable<Character, String>> mergedVector = new Vector<Hashtable<Character, String>>();
// Considering every vector has the same size
for (int i = 0; i < vector1.size(); i++) {
mergedVector.add(vector1.get(i));
mergedVector.add(vector2.get(i));
mergedVector.add(vector3.get(i));
}
// Print the result
for (Hashtable<Character, String> hash : mergedVector) {
for (Entry<Character, String> set : hash.entrySet())
System.out.println("KEY: " + set.getKey() + ", VALUE: " + set.getValue());
System.out.println("\nNext hashtable.\n");
}
}