How to group similar objects

2

I hit my head and could not find a logic to do that. Well, I have a list of objects (Police): List and these objects have several properties, such as: organization, year, context and others.

What I need is to pass this list by one method and have the rest of a list of lists with the grouping of policies that have the same organization, year, and context.

If for example I have these 4 policies:

P1 - organização: USP, ano: 2015, contexto: A
P2 - organização: USP, ano: 2015, contexto: A
P3 - organização: UFCG, ano: 2014, contexto: B
P4 - organização: UFCG, ano:2014, contexto B

The objects P1 and P2 and the objects P3 and P4 are similar, the return should be two lists, one with P1 and P2 and one with P3 and P4. Could someone help me with logic? Thank you!

    
asked by anonymous 19.10.2015 / 06:30

1 answer

4

Create a Map to relate an object to the list of objects similar to it. Then iterate over your collection, checking if the object is already there and adding to the list, or if you are not creating a new list.

This method works best (i.e., it is simpler and more efficient) if the similarity criterion is given by equals and hashCode of its objects. If this is not the case, I suggest creating a wrapper that will operate this way.

Map<Policy, List<Policy>> semelhancas = new HashMap<Policy, List<Policy>>();
for ( Policy p : lista ) {
    List<Policy> semelhantes = semelhancas.get(p);
    if ( semelhantes == null )
        semelhancas.put(p, semelhantes = new ArrayList<Policy>());
    semelhantes.add(p);
}

Example using a wrapper :

class PolicyWrapper {
    private Policy policy;
    public PolicyWrappr(Policy policy) {
        this.policy = policy;
    }

    public boolean equals(Object o) {
        Policy outra = ((PolicyWrapper)o).policy;
        // Chama o(s) método(s) de Policy que determina(m) se os dois são "similares"
    }

    public int hashCode() {
        // Cria um hash code a partir dos atributos de Policy que caracterizam "semelhança"
    }
}

Map<PolicyWrapper, List<Policy>> semelhancas = ...
for ( Policy p : lista ) {
    List<Policy> semelhantes = semelhancas.get(new PolicyWrapper(p));
    ...
    
19.10.2015 / 10:44