Count duplicate values in list

Asked

Viewed 3,168 times

3

I have a ArrayList with multiple numbers inside it. I need to identify how many times each number appears and then eliminate redundancies. I was able to eliminate redundancies, but I’m having big problems identifying how many of them there are.

What you can do so far:

private List<Calculos> RemoverDuplicados()
{
    aux = new ArrayList<Calculos>();
    ids = new ArrayList<Integer>();

    int[] intArray = new int[aux.size()];

    //separa os cálculos repetidos e envia para a lista auxiliar;
    for(Calculos i : calculosItems)
    {
        //se a variável 'ids' não tiver o valor do ID do produto, eu adiciono aqui
        if(!ids.contains(Integer.valueOf(i.getId_produto())))
        {
            aux.add(i);
            ids.add(Integer.valueOf(i.getId_produto()));
        }
    }

    for(Calculos i : aux){
        Log.d(TAG,"ID: " + i.getId_produto() + " possui: ? calculos");;
    }

    return aux;
}

These are the values (which are inside the database):

2
1
2
2
2
2
2
1
3
3
3
3
4
5
5
6
6
6

The current output is:

D/﹕ ~~ Calculos depois:
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 2 possui: ? calculos
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 1 possui: ? calculos
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 3 possui: ? calculos
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 4 possui: ? calculos
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 5 possui: ? calculos
05-16 19:48:23.586  28643-28643/com.financeiro.coolkey.financeiro_2 D/﹕ ID: 6 possui: ? calculos

In place of ? he should show me the number of calculations, for example: ID 1 possui 2 calculos.

Can someone help me, please?

  • How can you remove duplicates so you know the duplicate values, right? If yes, to check the frequency of each value see #frequency, maybe I can help you.

  • Yes, my good friend. I found this Frequency in my searches, but I was confused because I don’t know where exactly in the code I should add it and what parameters. For example, I know I have six Ids in this case. I wish I had 1 array that I could store the number of frequencies of each ID, but I can’t think of a logic for that :(

  • Do you want, for example, to have a map that contains the amount of each ID? That is, in a map with key and integer value, for the key where ID 2 has value 6?

  • Exactly, my dear! I’m glad you understand my problem, I have difficulties in clarifying things, hehe. :)

  • Okay, I’ve already put it on for you and you tell me if this is what you need.

  • Perfect, thank you very much for the consideration!

Show 1 more comment

2 answers

2


Starting from the posted in your question you know the duplicates so to check the frequency of each value you can use #frequency() of Collections.

You said in the comments that you need to store the amount of Ids for each ID. One way to do this is by using a map where the key (key) would be id and the value would be the quantity.

An example, starting a list with the Ids you have would be this:

final List<Integer> ids = Arrays.asList(2, 1, 2, 2, 2, 2, 2, 1, 3, 3, 3, 3, 4, 5, 5, 6, 6, 6);

final Map<Integer, Integer> idQuantidade = new HashMap<>();

idQuantidade.put(1, Collections.frequency(ids, 1));
idQuantidade.put(2, Collections.frequency(ids, 2));
idQuantidade.put(6, Collections.frequency(ids, 6));

So to print out each value we would have something like this:

final String format = "ID: %d possui: %d calculos";
final Set<Integer> chaves = idQuantidade.keySet(); // as chaves são os ids
for (final Integer chave : chaves) {
    System.out.println(String.format(format, chave, idQuantidade.get(chave)));
}

Which will display the following:

ID: 1 possui: 2 calculos
ID: 2 possui: 6 calculos
ID: 6 possui: 3 calculos

Another way, in Java 8+, would be to use the method #compute() of Map.

final Map<Integer, Integer> idQuantidade = new HashMap<>();

ids.forEach(id -> idQuantidade.compute(id, (chave, valor) -> (valor == null ? 1 : valor + 1)));

In this way, we iterate the values of the list and fill the map, using the id as key and the value equal to 1 when there is no key -> value in maps or incrementing in 1 whenever already exists as a key an id. The printing of each value would be something like this:

idQuantidade.forEach((chave, valor) -> System.out.println(String.format("ID: %d possui: %d calculos", chave, idQuantidade.get(chave))));

Which will display the following:

ID: 1 possui: 2 calculos
ID: 2 possui: 6 calculos
ID: 3 possui: 4 calculos
ID: 4 possui: 1 calculos
ID: 5 possui: 2 calculos
ID: 6 possui: 3 calculos

You can also have your own data structure, at your discretion, depending on your context.

  • Man, you’re a genius, thank you so much! It worked perfectly, brother!!!

0

Once you have the values in a BD, why not get this data already in the form you want?

Assuming your BD access class is db and that the name of the column that wants to know the number of occurrences is produtoId, the following code obtains a Cursor with the sum of occurrences of produtoId and writes a log for each one:

Cursor cursor = db.rawQuery(
        "SELECT produtoId, count(*) FROM nomeDaSuaTabela GROUP BY produroId", null);
while (cursor.moveToNext()) {
    Log.d(TAG,"ID: " + cursor.getInt(0) + " possui: cursor.getInt(1) calculos");
}
cursor.close(); 

Browser other questions tagged

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