【问题标题】:How can I compare two Object arrays and put the information in another one?如何比较两个对象数组并将信息放入另一个数组?
【发布时间】:2014-10-11 03:36:26
【问题描述】:

我有一个问题,我正在尝试比较两个arraylist,以便我可以将另一个完整的信息作为一个,问题如上所述:

我有这个问题:

 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;
}

我有另一个查询,它只是更改 glpi_tickettasks.taskcategories_id = 3(只是数字),这是因为在我们公司,我们将服务指定为远程或 presencial(我尝试从查询中获取信息,但我不是无法得到我想要的)

在执行两个查询后,我得到两个带有对象的 Arraylist,其中一个具有以下数据: 名称:(实体名称) 远程时间:1.5

和其他: 名称(实体名称) 呈现时间:5.5

因为我想在网页上显示该信息,所以我制作了一个具有以下代码的控制器:

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);
            }

        }
    }

如您所见,我有一个 If 用于评估哪个数组具有最大值我的意思是哪个数组更大,这是因为我认为最好的方法是使用普通 for 来读取数组,但随后谷歌搜索我找到了THIS LINK,然后我尝试使用 for:each 来解决问题,但是当我执行一些证明时,我意识到该对象已进入新数组数百次所以什么我想实现的是我想比较两个数组,如果远程数组上不存在远程实体,则应将其添加到新的数组列表中,但如果远程对象上的实体确实存在,那么我想将远程时间添加到该对象,然后将其添加到新的数组列表中,但它不起作用,因此非常欢迎提出建议。

PD:哦差点忘了,你看到的 Br 是用来调试的,只是为了知道正在处理什么。

【问题讨论】:

    标签: java arraylist compare


    【解决方案1】:

    无论哪种情况,您的代码都会将对象添加到 resultado: a) presencial 存在于 remoto b) remoto 中不存在 presencial。

    当你为“presential”做“remoto”时,你将把每个对象放在presential中,并将其与remoto中的每个对象进行比较。当您在 remoto 中找到对象时,您应该中断比较,否则您会“意识到该对象已进入新数组数百次”。

    我已经调整了你的代码

    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;
    }
    

    和 if 块

    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);
            }
        }
    }
    

    如果完全采用您的代码,那么需要注意的部分是:

     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());
         }
     }
    

    :)

    【讨论】:

    • 哇,非常感谢您的帮助,现在我已经接近解决方案了,但我有一些问题要问,看看我想要达到的内容如下:
    • 如果远程名称上存在当前对象名称,则应将远程时间添加到当前对象,并将当前对象添加到新的数组列表中,但如果远程对象中不存在当前对象,则应被添加到新的数组列表中,最后如果远程上的对象在当前不存在,它应该被添加到新的数组列表中,那么我该如何实现呢?我正在考虑另一个:每个来评估最后一个条件,但我真的不知道这是否是最好的解决方案。
    • 是什么阻碍了您使用另一个 for 来实现它?我也不知道这是否是最好的解决方案。 :)
    • 我好像根本没有红代码所以我今晚试试,我会告诉你的。
    • 它没有用,它不断重复呈现对象很多次,现在使用此代码,呈现对象永远不会被 remote.getitemporemoto 填充。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2022-01-20
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    相关资源
    最近更新 更多