Question

I check my case I have a listing where a process after the data is loaded with this information:

-> ExpAdminBean [codTipoExpediente=1, desTipoExpediente=Exp Coactivo, siNumSecuencia=2, nroDocumento=null]
-> ExpAdminBean [codTipoExpediente=19, desTipoExpediente=R Sancion, siNumSecuencia=0, nroDocumento=218-056-02742669]
-> ExpAdminBean [codTipoExpediente=2, desTipoExpediente=Rec, siNumSecuencia=0, nroDocumento=220-041-01169690]
-> ExpAdminBean [codTipoExpediente=19, desTipoExpediente=R Sancion, siNumSecuencia=0, nroDocumento=218-056-03048986]
-> ExpAdminBean [codTipoExpediente=2, desTipoExpediente=Rec, siNumSecuencia=0, nroDocumento=220-041-01169690]
-> ExpAdminBean [codTipoExpediente=23, desTipoExpediente=CIR, siNumSecuencia=0, nroDocumento=218-174-00146216]
-> ExpAdminBean [codTipoExpediente=2, desTipoExpediente=Rec, siNumSecuencia=0, nroDocumento=220-041-01169690]

What I have to do to eliminate duplicate records but the nroDocumento attribute, the attribute nroDocumento not be repeated, if any should be removed repeated, I wanted to use a Hash Set, but also is present as null, which complicates little.

My code Java:

Map<String, Set<ExpAdminBean>> map = new ConcurrentHashMap<String, Set<ExpAdminBean>>();   
Set<ExpAdminBean> setExpAdmin = null;
for(ExpAdminBean exp : listaExpAdminAux) {
    setExpAdmin = new HashSet<ExpAdminBean>();      
    map.put(exp.getNroDocumento(), setExpAdmin);                
}           

List<String> listExp = new ArrayList<String>(); 
for(String keySist : map.keySet()){                  
    listExp.add(keySist);
}
Was it helpful?

Solution

A collection without duplicates (how to determine duplicates being up to you) is a Set. A collection that maintain an arbitrary order is a List (in ArrayList the default order is the order of insertion). Note that list MAINTAIN an order ... but does not necessarily sort its elements.

Anyway if you want to keep the insertion order AND keep out duplicates you can use a LinkedHashSet<>.

In your case you need to reimplement the equals(~) and hashCode() functions of your ExpAdminBean class if possible. I suggest you implement it so that equals returns true when nroDocumento is equal and return the hashCode of nroDocumento dirrectly in the new hashCode implementation.

Otherwize if you cannot do that I suggest you use a map:

Map<String, ExpAdminBean> map = ~~~~~~ ;
for(ExpAdminBean exp : listaExpAdminAux) {
    if(!map.containsKey(exp.getNroDocumento())
        map.put(exp.getNroDocumento(), exp);                
} 
//if you need to put the values in a list you can do ...
ArrayList<ExpAdminBean> theList = new ArrayList<>(map.size());
theList.addAll(map.values());

Like I said before if you want to keep the "insertion order" of your first list you should use a LinkedHashMap<> or a LinkedHashSet<>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top