1

I have a problem, I'm trying to compare two arraylist so that I can fullfile another with the information as one, the problem is described above:

I have this query:

 public ArrayList consultaEntidadPresencial (GlpiEntities gentities){
    ArrayList consulta = new ArrayList();
    try {
        cnn=Conectar.getInstace();
        ps=cnn.prepareStatement("SELECT\n" + "glpi_entities.name,\n" + "Sum(glpi_tickettasks.actiontime)/3600 AS Tiempo\n" + "FROM\n" + "glpi_tickettasks\n" + "INNER JOIN glpi_tickets ON glpi_tickets.id = glpi_tickettasks.tickets_id\n" + "INNER JOIN glpi_entities ON glpi_tickets.entities_id = glpi_entities.id\n" + "WHERE\n" + "glpi_tickettasks.date BETWEEN ? AND ? AND\n" + "glpi_tickettasks.taskcategories_id = 4\n" +"GROUP BY\n" + "glpi_entities.name");
        ps.setDate(1,gentities.getfInicial());
        ps.setDate(2, gentities.getfFinal());
        rs=ps.executeQuery();
        while(rs.next()){
            GlpiEntities gtickets=new GlpiEntities();
            gtickets.setName(rs.getString(1));
            gtickets.setTiempoPresencial(rs.getDouble(2));

            consulta.add(gtickets);
        }
    } catch (NamingException ex) {
        Logger.getLogger(TasksDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(TasksDao.class.getName()).log(Level.SEVERE, null, ex);
    }

    return consulta;
}

And I have another Query which just changes glpi_tickettasks.taskcategories_id = 3 (just the number), this is because at our company we specify services as remote or presencial (I've tried getting the information from the query but I wasn't able to get what I wanted)

afther executing both querys I get two Arraylist with the objects on it, one has the following Data: Name: (entitie name) RemoteTime: 1.5

and the other: Name (entitie name) PresentialTime:5.5

and as I want to show that information on the web page then I've made a controller which has the following code:

if(request.getParameter("entidad")!=null && request.getParameter("entidad").equals("Enviar")){
        String fInicial=request.getParameter("inicial");
        String fFinal= request.getParameter("final");
        if(fInicial.length()<19 || fFinal.length()<19){
            response.sendRedirect("reportes/Reportegeneral.jsp?msg=Las fechas deben ser ingresadas con el formato Año-Mes-Día horas-minutos-segundos.");
        }else{
            GlpiEntities entities=new GlpiEntities();
            try {
                Date inicial=formatter.parse(fInicial);
                Date fechaF=formatter.parse(fFinal);
                fi=new java.sql.Date(inicial.getTime());
                ff=new java.sql.Date(fechaF.getTime());
                int arraySize=0;
                entities.setfInicial(fi);
                entities.setfFinal(ff);
                ArrayList<GlpiEntities> presencial=tdao.consultaEntidadPresencial(entities);
                ArrayList<GlpiEntities> remoto=tdao.consultaEntidadRemoto(entities);
                List<GlpiEntities> resultado= new ArrayList<GlpiEntities>();
                if(presencial.size()>remoto.size()){
                    arraySize=presencial.size();
                }else if (remoto.size()>presencial.size()) {
                    arraySize=remoto.size();
                }

                for (GlpiEntities presential: presencial){
                    for(GlpiEntities remote: remoto){
                        if(!presential.getName().equals(remote.getName())){
                            //out.print(" <br/> el valor de primer if es: "+presential.getName());
                            resultado.add(presential);
                        }else if(presential.getName().equals(remote.getName())){
                            presential.setTiempoRemoto(remote.getTiempoRemoto());
                            //out.print(" <br/> el valor de primer if es: "+presential.getName()+" Valor de remoto"+remote.getName());
                            resultado.add(presential);
                        }
                    }
                    for(GlpiEntities listado: resultado){
                        out.print(" <br/> Nombre entidad: "+listado.getName());
                        out.print(" <br/> Tiempo Presencial: "+listado.getTiempoPresencial());
                        out.print(" <br/> Tiempo Remoto: "+listado.getTiempoRemoto());
                    }
                }

                sesion.setAttribute("entidaddetalle", resultado);
                response.sendRedirect("reportes/Reportegeneral.jsp?resul=ok");




            } catch (ParseException ex) {
                Logger.getLogger(ReporteCtrol.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

As you can see I have an If which evaluates which of the arrays has the higest value I mean which one is the bigger one, this was beacuse I thought the best way was using a normal for to read the arrays but then afther a google search I've found THIS LINK and then I've tried to use a for:each to solve the problem but when I was performing some proofs I've realized that the object was into the new array Hundreds of times so what I want to achieve with this is I want to compare the two arrays and if the entities which is on remote doesn't exist on precenial array then it should be added to a new arraylist, but if the entitie on remote object does exists then I want to add remote time to that objet and then add it to the new arraylist, but it doesn't work so suggestions are very welcome.

PD: oh almost forgot it, the Br you see are for debugging just to know what is being processed.

Community
  • 1
  • 1
Leo21
  • 13
  • 1
  • 7

1 Answers1

1

Your code adds the object to resultado at either case: a) presencial exists in remoto b) presencial doesn't exist in remoto.

When you do for "presential", for "remoto" then you are taking each object in presential and comparing it to each object in remoto. When you find object in remoto, you should then break the comparison, otherwise you get "realized that the object was into the new array Hundreds of times ".

I've tweaked your code

public List<GlpiEntities> consultaEntidadPresencial(GlpiEntities gentities) 
{
    List<GlpiEntities> consulta = new ArrayList<GlpiEntities>();
    try 
    {
        cnn = Conectar.getInstace();
        ps  = cnn.prepareStatement(
                "SELECT\n" 
                + "glpi_entities.name,\n" 
                + "Sum(glpi_tickettasks.actiontime)/3600 AS Tiempo\n"
                + "FROM glpi_tickettasks\n" 
                + "INNER JOIN glpi_tickets ON glpi_tickets.id = glpi_tickettasks.tickets_id\n" 
                + "INNER JOIN glpi_entities ON glpi_tickets.entities_id = glpi_entities.id\n" 
                + "WHERE\n" + "glpi_tickettasks.date BETWEEN ? AND ? AND\n" + "glpi_tickettasks.taskcategories_id = 4\n" 
                + "GROUP BY\n" + "glpi_entities.name");
        ps.setDate(1, gentities.getfInicial());
        ps.setDate(2, gentities.getfFinal());
        rs = ps.executeQuery();
        while (rs.next()) 
        {
            GlpiEntities gtickets = new GlpiEntities();
            gtickets.setName(
                    rs.getString(1));
            gtickets.setTiempoPresencial(
                    rs.getDouble(2));

            consulta.add(gtickets);
        }
    }
    catch (NamingException ex) 
    {
        Logger.getLogger(TasksDao.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch (SQLException ex)
    {
        Logger.getLogger(TasksDao.class.getName()).log(Level.SEVERE, null, ex);
    }

    return consulta;
}

and the if block

if (null != request.getParameter("entidad")
        && request.getParameter("entidad").equals("Enviar"))
{
    String fInicial = request.getParameter("inicial");
    String fFinal   = request.getParameter("final");

    if (fInicial.length() < 19
            || fFinal.length() < 19) 
    {
        response.sendRedirect(
                "reportes/Reportegeneral.jsp?msg=Las fechas deben ser ingresadas con el formato Año-Mes-Día horas-minutos-segundos.");
    }
    else
    {
        GlpiEntities entities = new GlpiEntities();
        try {
            Date inicial = formatter.parse(fInicial);
            Date fechaF  = formatter.parse(fFinal);
            fi = new java.sql.Date(
                    inicial.getTime());
            ff = new java.sql.Date(
                    fechaF.getTime());
            entities.setfInicial(fi);
            entities.setfFinal(ff);
            List<GlpiEntities> presencial = tdao.consultaEntidadPresencial(entities);
            List<GlpiEntities> remoto     = tdao.consultaEntidadRemoto(entities);
            List<GlpiEntities> resultado  = new ArrayList<GlpiEntities>();

            List<GlpiEntities> largerList = presencial.size() > remoto.size() ? presencial : remoto;
            List<GlpiEntities> smallerList = presencial.size() > remoto.size() ? remoto : presencial;

            if (presencial.size() == remoto.size())
            {
                largerList  = presencial;
                smallerList = remoto;
            }

            /** temporary values */
            boolean      exists = false;
            GlpiEntities tremote = null;

            for (GlpiEntities presential : presencial)
            {
                exists  = false;
                tremote = null ;

                for (GlpiEntities remote : remoto) 
                {
                    if (presential.getName().equals(remote.getName()))
                    {
                        exists  = true;
                        tremote = remote;
                        break;
                    }
                    /*
                    if (!presential.getName().equals(remote.getName())) 
                    {
                        //out.print(" <br/> el valor de primer if es: "+presential.getName());
                        resultado.add(presential);
                    } 
                    else if (presential.getName().equals(
                                remote.getName())) 
                    {
                        presential.setTiempoRemoto(
                                remote.getTiempoRemoto());
                        //out.print(" <br/> el valor de primer if es: "+presential.getName()+" Valor de remoto"+remote.getName());
                        resultado.add(presential);
                    }
                    */
                    if (exists)
                    {
                        presential.setTiempoRemoto(
                                tremote.getTiempoRemoto());
                    }
                    resultado.add(presential);
                }
            }

            for (GlpiEntities remote : remoto) 
            {
                exists  = false;    

                for (GlpiEntities presential : presencial)
                {
                    if (remote.getName().equals(presential.getName()))
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    resultado.add(presential);
                }
            }

            for (GlpiEntities listado : resultado) 
            {
                out.print(" <br/> Nombre entidad: "    + listado.getName());
                out.print(" <br/> Tiempo Presencial: " + listado.getTiempoPresencial());
                out.print(" <br/> Tiempo Remoto: "     + listado.getTiempoRemoto());
            }

            sesion.setAttribute("entidaddetalle", resultado);
            response.sendRedirect("reportes/Reportegeneral.jsp?resul=ok"); 
        } 
        catch (ParseException ex) 
        {
            Logger.getLogger(
                    ReporteCtrol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

If taking exactly your code then the part to pay attention would be:

 boolean      exists  = false;
 GlpiEntities tremote = null ;

 for (GlpiEntities presential: presencial){
     exists  = false;
     tremote = null ;
     for(GlpiEntities remote: remoto){
         if(presential.getName().equals(remote.getName())){
             exists  = true;
             tremote = remote;
             break;                                                 
         }
     }
     if (exists) {
         presential.setTiempoRemoto(tremote.getTiempoRemoto());
         //out.print(" <br/> el valor de primer if es: "+presential.getName()+" Valor de remoto"+remote.getName());
     }
     resultado.add(presential);

     for(GlpiEntities listado: resultado){
         out.print(" <br/> Nombre entidad: "+listado.getName());
         out.print(" <br/> Tiempo Presencial: "+listado.getTiempoPresencial());
         out.print(" <br/> Tiempo Remoto: "+listado.getTiempoRemoto());
     }
 }

 for(GlpiEntities remote: remoto){
     exists  = false;
     for (GlpiEntities presential: presencial){
         if(remote.getName().equals(presential.getName())){
             exists  = true;
             break;                                                 
         }
     }
     if (!exists) {
         resultado.add(presential);
     }

     for(GlpiEntities listado: resultado){
         out.print(" <br/> Nombre entidad: "+listado.getName());
         out.print(" <br/> Tiempo Presencial: "+listado.getTiempoPresencial());
         out.print(" <br/> Tiempo Remoto: "+listado.getTiempoRemoto());
     }
 }

:)

  • Wow thank you so much for your helpl, now I'm near to reach the solution but I have something to ask, look what I wanted to reach is the following: – Leo21 Oct 19 '14 at 20:14
  • If the presential object name exists on remote name then the remote time should be added to presential and the presential object added to a new arraylist but if the object in presential doesn't existis on remote then it should be added to the new arraylist and finally if the objet on remote doesn't exists on presential it should be added to the new arraylist, so how can I achieve this? I was thinking of another for:Each to evaluate tha last condition but I don't really know if it's the best solution. – Leo21 Oct 19 '14 at 20:56
  • What is keeping you from implementing it with another _for_? I don't know either if it's the best solution. :) – Developer Marius Žilėnas Oct 20 '14 at 05:32
  • It seems like I haven't red the code at all so I'll try tonight and I'll let you know. – Leo21 Oct 20 '14 at 16:12
  • It haven't worked, it keeps repeating presential objects lots of times and now with this code the presential object is never filled with remote.getitemporemoto. – Leo21 Oct 23 '14 at 03:12
  • How come can the presential repeat many times with this code? Can you show data items (you use to test) from presencial and data items from remoto here? – Developer Marius Žilėnas Oct 23 '14 at 05:54
  • Hello and tanks Marius, I finally found the error, the error was that in the second tweaked code you putted another for printing what the new list hast in it so It was showing so much grabacge but i've deleted that an it's okey, now I need to order this array but maybe it could be for another post if google doesn't bring the help I need, so thank you so much. – Leo21 Oct 26 '14 at 19:41