Search code examples
javajasper-reports

How to setup my Hashmap <key, list> as a datasource for jasper reports


I have requirement to display HashMap object as jasper datasource

Map<String, List<obj>> salesMap= new HashMap<>();    
salesMap.put("10/02/2021", List<Obj>);
salesMap.put("11/02/2021", List<Obj>);
salesMap.put("12/02/2021", List<Obj>);

and my datasource

private JRMapCollectionDataSource fuelSalesDataSource;

public Map<String, Object> getDataSources() {
    Map<String, Object> dataSources = new HashMap<>();
    dataSources.put("fuelSalesDataSource", fuelSalesDataSource);
    return dataSources;
}

and my jasper print

    JRMapArrayDataSource dataSource = new JRMapArrayDataSource(
            new Object[] { fuelSalesReportInputMO.getDataSources() });

    JasperReport jasperReport = JasperCompileManager.compileReport(fuel_sales_report);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, fuelSalesReportInputMO.getParameters(),
            dataSource);

    reportData = JasperExportManager.exportReportToPdf(jasperPrint);

I have to display the my HashMap in jasper, how to get hash map key and it list of objects in one single row?

       key column          value column          value column     
       10/02/2021         list[0].getType       list[1].getType
       11/02/2021         list[0].getType       list[1].getType.

I have field in jrmxl

<field name="fuelSalesDataSource" class="net.sf.jasperreports.engine.data.JRMapCollectionDataSource"/>

 

How to read map in jrxml by key and its values as list?


Solution

  • i have fixed the issue, and as pointed out by @Petter, i changed my datasource to JRBeanCollectionDataSource from JRMapCollection...

    code below

    public JRBeanCollectionDataSource  getFuelSalesReportDataSource() {
        Map<String, List<DailyFuelSalesMO>> sortedMap = new TreeMap<>(dailyFuelSalesMap);
        Set<Entry<String,List<DailyFuelSalesMO>>> set = sortedMap.entrySet();
        fuelSalesReportDataSource = new JRBeanCollectionDataSource(set);
        return fuelSalesReportDataSource;
    }
    

    and jrxml, i have fields as below..

        <field name="key" class="java.lang.String"/>
        <field name="value[0].fuelObj.type" class="java.lang.Object"/>
        <field name="value[0].fuelObj.priceObj.price" class="java.lang.Double"/>         
        <field name="value[1].fuelObj.type" class="java.lang.Object"/>
        <field name="value[1].fuelObj.priceObj.price" class="java.lang.Double"/>
    

    so i could able to populate in single row, with key, and its list values, in this i have two list object per key, so i could able to get those objects by value[i] for each key object in the hashmap...