Remove duplicate objects from ListMinhaClass

3

Galera is as follows, I have a model class with attributes that store data returned from the database. For example:

public class RelacaoTransformacao {
    /** ID do registro no banco de dados. */
    private long id;
    /** Indica se o teste já foi concluído. */
    private boolean concluido;
    /** O valor do teste. */
    private double valor;
    // ...O restante do código.
}

Having the code below as an example:

// Percorre o cursor obtendo todos os dados e criando um objeto com os dados retornados.
            while ( result.moveToNext() ) {
                long id = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_ID.texto ) );
                boolean concluido = result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_CONCLUIDO.texto ) ) > 0 ;
                double valor = result.getDouble( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_VALOR.texto ) );
                int polaridade = result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_POLARIDADE.texto ) );
                String observacao = result.getString( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_OBSERVACAO.texto ) );
                long idPrimario = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_FK_ENROLAMENTO_TCTP_ID1.texto ) );
                long idSecundario = result.getLong( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.RelacaoTransformacao.COLUNA_FK_ENROLAMENTO_TCTP_ID2.texto ) );
                String primario = result.getString( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.EnrolamentoTcTp.COLUNA_ENROLAMENTO.texto ) );
                primario += String.valueOf( result.getInt( result.getColumnIndex( br.com.bhdnet.softencal.app.database.enums.EnrolamentoTcTp.COLUNA_NUMERO_ENROLAMENTO.texto ) ) );

                RelacaoTransformacao relacaoTransformacao = new RelacaoTransformacao( id, concluido, valor, polaridade, observacao, idPrimario, idSecundario, primario, null );
                // Adiciona o objeto enrolamento a lista de enrolamentos
                listRelacaoTransformacao.add( relacaoTransformacao );
            }

I will always have two objects repeated in my list by attribute ID, this due to my search in the database (I do not need to explain this search, just understand that I really need to return two records repeated because in a record column repeated value will be different and I need to get this value). How do I get one of these objects repeated by ID and then remove it from the list?

    
asked by anonymous 30.05.2014 / 20:50

2 answers

6

You can do a for inside the other, scrolling through the list and storing in different variables each object in the list, from there you compare the id, if the id is the same and it is not the same object you enter your logic of choosing which of the two should be removed.

Add these elements that should be removed in a separate list to remove them after checking inside the fors.

Example:

public class LucasSantos {
    public static void main(String[] args) {
        List<RelacaoTransformacao> listRelacaoTransformacao = new ArrayList<>(); 
        List<RelacaoTransformacao> listEliminar = new ArrayList<>(); 
        listRelacaoTransformacao.add(new RelacaoTransformacao(1, true, 2));
        listRelacaoTransformacao.add(new RelacaoTransformacao(1, true, 5));
        listRelacaoTransformacao.add(new RelacaoTransformacao(2, true, 5));
        listRelacaoTransformacao.add(new RelacaoTransformacao(2, true, 1));
        System.out.println("Antes");
        for(RelacaoTransformacao r: listRelacaoTransformacao) {
            System.out.println(r);
        }

        // Faz um for percorrendo os itens da lista. Para cada item da lista percorrido, faz um outro for para percorrer todos os itens da lista novamente (Pulando o primeiro item do for externo)
        // para verificar qual objeto tem id igual ao objeto do for mais externo e se são objetos diferentes.
        for ( int i = 0; i < listRelacaoTransformacao.size(); i++ ) {
            for ( int j = i + 1; j < listRelacaoTransformacao.size(); j++ ) {
                // Se os objetos tiverem o mesmo id mas forem objetos diferentes, entao pegamos o campo primario do segundo objeto e o colocamos no campo secundario da primeiro objeto.
                // Adicionamos o segundo objeto na lista para eliminação de objetos repetidos.
                if ( listRelacaoTransformacao.get( i ).getId() == listRelacaoTransformacao.get( j ).getId() &&
                    !( ( (Object) listRelacaoTransformacao.get( i ) ).equals( listRelacaoTransformacao.get( j ) ) )  ) {

                    // Aqui você faz o que quiser.
                    i++; // Incrementa i em 1 para evitar verificações desnecessárias.
                    break;
                }
            }
        }
        //elimina todos os elementos que foram marcados para remoção
        listRelacaoTransformacao.removeAll(listEliminar);
        System.out.println("Depois");
        for(RelacaoTransformacao r: listRelacaoTransformacao) {
            System.out.println(r);
        }
    }
}

Output:

  

Before
  RelationTransformation [id = 1, completed = true, value = 2.0]
  RelationTransformation [id = 1, completed = true, value = 5.0]
  RelationTransformation [id = 2, completed = true, value = 5.0]
  RelationTransformation [id = 2, completed = true, value = 1.0]
  RelationTransformation [id = 3, completed = true, value = 2.0]
  Afterwards   RelationTransformation [id = 1, completed = true, value = 2.0]
  RelationTransformation [id = 2, completed = true, value = 1.0]

Note : Whenever you make object comparisons override the equals () method, and if you are working with Set, also override hashCode (). The List interface does not use the hashCode () method however the documentation itself recommends that you always overwrite it when overwriting the equals. The Object class documentation says:

  equals (): Note that it is generally necessary to override the hashCode method whenever this method is overridden, only to maintain the hashCode general contract, which states that equal objects must have hash codes.

Free translation:

  

equals (): Note that it is usually necessary to override the hashCode method whenever this method is overwritten because it maintains the hashCode method contract, which says that equal objects must have equal hash codes.

More information on what the hashCode () method is:

How important is it to implement the hashCode method in Java?

Documentation: equals () , Class Object - Java SE 7

    
30.05.2014 / 21:03
7

Use a class that implements a set ( Set ), such as TreeSet . Please provide a Comparator in the constructor that uses the ID.

Classes that implement Set only allow distinct elements, using as a parameter the fields used in Comparator .

    
30.05.2014 / 21:05