I have a variable List. Its declaration is like :
List<HashMap<String, Object>>
Sample data in it:
[{total-expense=228, company=HiHard, year=2009}, {total-expense=2936, company=POTENT, year=2009}, {total-expense=1362412.65, company=HiHard, year=2010}, {total-expense=9007.96, company=POTENT, year=2010}, {total-expense=240427.43, company=HiHard, year=2011}, {total-expense=1956.11, company=POTENT, year=2011}]
I have written a program to fetch the below result:
{"HiHard":[[228,1362412.65,240427.43]],"POTENT":[[2936,9007.96,1956.11]]}
i.e. to fetch company-wise total expense incurred for financial years 2009, 2010, 2011.
Current program logic:
1) getDistinctCompanies from the list
2) Iterate through the distinct companies[from step 1] and get the expense incurred by passing in company and list.
Complete program:
public class JSONConstruction {
public static void main(String[] args) {
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
... ASSUME list has the SAMPLE data as described before.
List<String> companyList = getDistinctCompanies(list);
Iterator<String> iterCompany = companyList.iterator();
String company;
JSONObject obj = new JSONObject();
while(iterCompany.hasNext()){
company = iterCompany.next();
JSONArray jsonList = new JSONArray();
jsonList.add(getExpenseList(list, company));
obj.put(company, jsonList);
}
System.out.print(obj);
}
private static List<String> getDistinctCompanies(List<HashMap<String, Object>> list) {
Iterator<HashMap<String, Object>> iterList = list.iterator();
String company;
List<String> companyList = new ArrayList<String>();
while (iterList.hasNext()) {
HashMap<String, Object> map = iterList.next();
company = (String) map.get("company");
if(companyList==null || (!companyList.contains(company))) {
companyList.add(company);
}
}
return companyList;
}
private static List<Object> getExpenseList(List<HashMap<String, Object>> list, String company) {
Iterator<HashMap<String, Object>> iterList = list.iterator();
List<Object> expenseList = new ArrayList<Object>();
String companyMatch;
while (iterList.hasNext()) {
HashMap<String, Object> map = iterList.next();
companyMatch = (String) map.get("company");
if(companyMatch.equals(company)) {
Object obj = map.get("total-expense");
expenseList.add(obj);
}
}
return expenseList;
}
Though the data is fetched correctly, I am eager to know a better way of coding this program.