Java: Add HashMap to ArrayList for Talend

Viewed 587

I am using Talend tJavaFlex component where there is start code(runs once in the beginning), main code(runs for every row), end code(runs once at end).

**In the start code(create an empty list):**
java.util.List sharedList=new java.util.ArrayList<>(); 

**In the main code(create HashMap for each row and add to list):**
Consider each row has fields: startId, endID, time, flag.

sharedList.add(new java.util.HashMap<String, String>("startId",row1.startId));
<I am not sure how to handle this part>

**In end code(expose the list to other components)**
System.out.print(sharedList.size());

Could you suggest how to create HashMap for each row and add to list.

2 Answers

You need to correct your sharedList declaration from,

java.util.List sharedList=new java.util.ArrayList<>();

to

java.util.List<Map<String, String>> sharedList=new java.util.ArrayList<Map<String, String>>();

And your main code should be written something like this,

Map<String, String> rowDataMap = new HashMap<String, String>();
rowDataMap.put("startId",row1.startId);
rowDataMap.put("endID",row1.endID);
rowDataMap.put("time",row1.time);
rowDataMap.put("flag",row1.flag);
sharedList.add(rowDataMap);

Let me know if this looks fine and/or if you have any other queries.

You can create and initialize a HashMap and add it to a List at once like this,

List list = new ArrayList();

list.add(new HashMap() {{
    put("a", "b");
}});
Related