How to add duplicate values from an array of objects and keep only 1 of each duplicate object?

0

Hello, I have the following problem and I'm having a hard time resolving 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.

Summarized 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<>();

Then 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 sum total of all results with the same name. that returns like this

  

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

  (1)="FORMULA2", "1 + 1", "6"

    
asked by anonymous 19.05.2016 / 18:20

1 answer

0

I create a new arrayList called newitems, I get the original formulas arrayList "this.table.getItem" and compare it to the formulas generated using the comparator name. Once done I save the temporary object "it" in the new arrayList "newItems"

        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);
        }
    
19.05.2016 / 19:12