How to add duplicate values of an object arrayList and keep only 1 of each duplicated object?

Asked

Viewed 674 times

0

Hello I have the following problem and I’m having a lot of difficulty in solving it. I have a code that applies a mathematical formula. This formula ends up being applied several times. each time it generates an object the name and the result. The problem is that I have to add all objects that have the same name in a single result.

Summary example

class Formula(){
 private String nome;
 private String formula;
 private float resultado;
}

The list has elements with the same name and formula

ArrayList<Formula> resultados = new ArrayList<>();

So the list ends up having values like this

results.get(0) = "FOMULA1","2+4","6";

results.get(1) = "FOMULA1","2+4","6";

results.get(2) = "FOMULA1","2+4","6";

What I need is to generate a new Arraylist that contains the total sum of all results with the same name. so return

Outputs.get(0) = "FORMULA1","2+4","18"

Outputs.get(1) = "FORMULA2","1+1","6"

1 answer

0


I create a new arrayList called novositems, I take the original formulas arrayList "this.tabela.getItem" and compare it to the formulas generated using the name as comparator. After done I save the temporal object "it" in the new "newItems arrayList"

        ArrayList<Item> novosItems = new ArrayList<>();
        //Soma todos os duplicados.
        for(Item it: this.tabela.getItem()){
            float soma = 0;
            for(Item it2: listaItem){
                if(it.getNomeItem().equalsIgnoreCase(it2.getNomeItem())){
                    soma += it2.getResultado();
                    it.setResultado(soma);
                }
            }
            novosItems.add(it);
        }

Browser other questions tagged

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