How to group similar objects

Asked

Viewed 2,622 times

2

I’ve hit my head and I couldn’t find the logic to do it. Well, I have a list of objects (Police): List and these objects have several properties, for example: organization, year, context and others.

What I need is to pass this list by a method and have the rest of a list of lists with the grouping of policies that have equal 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 P1 and P2 objects and the P3 and P4 objects are similar, the return should be two lists, one with P1 and P2 and the other with P3 and P4. Could someone help me with logic? Thank you!

  • Two questions: Why these policies are not in a banco de dados, where could you simply run a query? And why can’t you iterar by comparing objects and creating a second list with the items you are looking for?

1 answer

5


Create a Map to relate an object to the list of objects similar to it. Then move on to 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 better (i.e. becomes simpler and more efficient) if the similarity criterion is given through the equals and hashCode of your objects. If not, I suggest creating a wrapper that operates that 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));
    ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.