Merge multiple ArrayList into a collection

0

It is possible to join 3 ArrayList into a collection and then send it as datasource to a report. Or do you have another way to do it?

I have 3 ArrayList of 3 objects, I wanted the information from these lists all together in one report.

Method that generates report:

public void gerarRelatorio(List list, int numeroRelatorio) {

    JasperReport report = null;

    try {
        InputStream inputStreamReal = getClass().getResourceAsStream("/br/com/xml/relatorio/RelatorioXml.jrxml");
        report = JasperCompileManager.compileReport(inputStreamReal);
    } catch (JRException ex) {
        Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        JasperPrint print = JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(list));
        JasperExportManager.exportReportToPdfFile(print,
                "C:\relatorios1/RelatorioClientes" + "0000" + numeroRelatorio + ".pdf");
    } catch (JRException ex) {
        Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Code where you pass the values of the 3 lists to one and sends it to the report:

JFileChooser chooser = new JFileChooser();
// Possibilita a seleção de vários arquivos
chooser.setMultiSelectionEnabled(true);

// Apresenta a caixa de diálogo
chooser.showOpenDialog(null);

//ListaAuxiliar <----------------
List<List> listaAuxiliar = new ArrayList<List>();

// Retorna os arquivos selecionados. Este método retorna vazio se
// o modo de múltipla seleção de arquivos não estiver ativada.
File[] files = chooser.getSelectedFiles();

for (File argumento : files) {
    System.err.println("Argumentos: " + argumento.getPath());
    caminho = argumento.getPath();
    LeitorXml parser = new LeitorXml();
    LeitorXml1 parser1 = new LeitorXml1();
    LeitorXml2 parser2 = new LeitorXml2();

    try {
        /* List<Cliente> */
        listaContatos = (ArrayList<UnimedGuia>) parser.realizaLeituraXML(caminho);
        listaContatosCabecalho = (ArrayList<UnimedGuiaCabecalho>) parser1.realizaLeituraXML(caminho);
        listaContatosLote = (ArrayList<UnimedGuiaLote>) parser2.realizaLeituraXML(caminho);

        System.out.println("Valores: " + listaContatos);
        System.out.println("Valores1: " + listaContatosCabecalho);
        System.out.println("Valores2: " + listaContatosLote);

        //Adiciona todas as listas  <--------------------
        lista.add(listaContatos);
        lista.add(listaContatosCabecalho);
        lista.add(listaContatosLote);

        listaAuxiliar.add(lista);
        //System.err.println("Lista Auxiliar: "+ listaAuxiliar1);
        System.out.println("Teste Ao Juntar Listas: "+lista);

    } catch (ParserConfigurationException e) {
        System.out.println("O parser não foi configurado corretamente.");
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("Problema ao fazer o parse do arquivo.");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("O arquivo não pode ser lido.");
        e.printStackTrace();
    }

}

//Enviar o relatório
int nRel = 0;
for (List lst : listaAuxiliar) {
    System.out.println("Numero do rel: " + nRel);
    System.out.println("LST: "+lst);
    gerarRelatorio(lst, nRel);

    nRel++;
}

iswhatappearsinOutput,whenIgiveSystem.out.println("LST: "+lst); and then when it enters the method to generate the report it gives it that:

:

    
asked by anonymous 15.04.2015 / 13:20

1 answer

1

Understand the requirements

From the information available, I could not understand how the information is read and how exactly it should be displayed.

It is a common mistake for programmers to try to change the code to arrive at a satisfactory result without having in mind very clearly what goal to achieve and how to handle the available data to reach this goal. >

From what I can extract from context, the idea goes something like this:

  

Read N XML files with tab information, each Tab consisting of some basic information, header and batch, consolidate this information into a single list, and generate a report.

Dividing the process in steps

The second point is to define exactly how you intend to do this. If the above requirement is true, you can think of the following tasks:

  • Map each XML file to an object or list of domain objects that represents the information in a Tab
  • Add all information in a list
  • Generate a report from the list
  • Mapping XML

    I know there is already a code for this. But it is strange to implement the question using 3 different parsers that return 3 different domain objects ( UnimedGuia , UnimedGuiaCabecalho and UnimedGuiaLote ).

    Modeling domain classes

    I imagine that the 3 classes mentioned above are related in some way.

    I may be completely mistaken, but it seems like UnimedGuia is the "main" entity and can have a header and multiple batches.

    If this is the case, it would be better to model the classes like this:

    public class UnimedGuia {
        UnimedGuiaCabecalho cabecalho;
        List<UnimedGuiaLote> lotes;
    }
    

    If it's just one batch per tab, it might look like this:

    public class UnimedGuia {
        UnimedGuiaCabecalho cabecalho;
        UnimedGuiaLote lote;
    }
    

    Then in the end you will only need a list of class UnimedGuia , since each item in the list will already include its header and batch.

    Without this relationship, putting object cabbage in a different list, eventually your logic can get lost and mix batches and headers from different tabs.

    Reading the XML correctly

    What do you have in each XML file?

    If each XML has only one tab, then you can return only one simple object, not one list.

    Preferably returns the tab already with the header and batch (s) as mentioned above in the modeling part.

    If you have multiple tabs in each XML, then return a list of tabs, but avoid parsing the file multiple times to avoid mixed data problems as mentioned above.

    Adding objects to a single list

    Consolidating lists is easy, but also confusing if you do not have well-defined data structures in mind.

    First, of course, we need a master list, but before that the most important thing to define is:

      

    A list of what?

    If the answer to a list of tabs, then the list will look like this:

    List<GuiaUnimed> guias = new ArrayList<>();
    

    Then, with each reading of a tab you need to add it in the main list. If it's a simple tab, use the add method of the list.

    Example:

    GuiaUnimed guia = parser.lerGuia(arquivo);
    guias.add(guia);
    

    However, if multiple tabs are read at the same time, do not use the add method because it always adds an item to the list. To add multiple items at the same time, use addAll .

    Example:

    List<GuiaUnimed> guiasLidosDoXML = parser.lerGuias(arquivo);
    guias.addAll(guiasLidosDoXML);
    

    The addAll method is equivalent to making a loop in the list of read guides and adding one by one to the main list.

    Generating the report

    If the idea is to generate only one report, then just skip the list above and that's it.

    On the other hand, if you need to generate multiple reports, then you will need to change the logic that I describe in the topics above. However, you will hardly need a list containing multiple lists, as you simply generate the report within the loop.

        
    15.04.2015 / 16:24