How to find the occurrence of equal integer values in a vector?

8

I need to find age frequency in a vector. I know how to do this when the vector is small, but not when it is large. Consider the following vector:

int[] idade = {15,18,15,20,16,30,18,45,43,14,25,16,20};

For this vector, I could do a sequential search to find how many people are the same age:

for(i = 0; i < idade.length; i++){
        if(idade[i] == 14) i14++;
        if(idade[i] == 15) i15++;
        if(idade[i] == 16) i16++;
        /*if(...*/
}

But I can not find a way to find the occurrence of equal ages when the vector has more than 1,000 positions. Can anyone give me a hint how this can be done?

Thank you very much!

    
asked by anonymous 06.09.2018 / 07:37

3 answers

5

My answer serves as an alternative to @SeverMateus without using streams and totalizing with a normal array like a HashMap . In this case it is simple to do because the range of possible values for ages is low.

Then the idea starts with creating a normal array for counting the ages, assuming a value at most, so that the case can be 200 :

int[] contagemIdades = new int[200];

Then the count is taken by taking each age, and summing in the corresponding position:

for (int i = 0; i < idades.length; ++i){
    int idade = idades[i];
    contagemIdades[idade]++;
}

After this has the counting vector built. Each position has the number of people with that age, which will be zero for those who did not appear.

To find out which ages have more than one person, simply check if the count is greater than or equal to 2:

for (int i = 0; i < contagemIdades.length; ++i) {
    if (contagemIdades[i] >= 2){ //apenas as idades que tem mais que uma pessoa
        System.out.printf("Existem %d pessoas com %d anos de idade\n", contagemIdades[i], i);
    }
}

See the code working on Ideone

Output:

Existem 2 pessoas com 15 anos de idade
Existem 2 pessoas com 16 anos de idade
Existem 2 pessoas com 18 anos de idade
Existem 2 pessoas com 20 anos de idade
    
06.09.2018 / 11:56
5

As an alternative to the War answer, you can implement using only libraries that are already part of Java:

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TestSorting {

public static void main(String[] args) {
    List<Integer> items = Arrays.asList(15,18,15,20,16,30,18,45,43,14,25,16,20);
    Map<Integer, Long> result =
            items.stream().collect(
                    Collectors.groupingBy(
                            Function.identity(), Collectors.counting()
                    )
            );

    Map<String, Long> finalMap = new LinkedHashMap<>();

    //Sort a map and add to finalMap
    result.entrySet().stream()
            .sorted(Map.Entry.<Integer, Long>comparingByValue()
                    .reversed()).forEachOrdered(e -> finalMap.put(String.valueOf(e.getKey()), e.getValue()));

    System.out.println(finalMap);
    //Output: {16=2, 18=2, 20=2, 15=2, 25=1, 43=1, 45=1, 14=1, 30=1}
}
}

If you want to see only the result of a member:

    System.out.println(finalMap.get("18"));
    //Output: 2
    
06.09.2018 / 11:12
4

One more way to solve this problem. A little simpler than the solution presented by @SeverMateus.

import java.util.*;

class Main {
    public static void main(String[] args) {
        List<Integer> items = 
                 Arrays.asList(15,18,15,20,16,30,18,45,43,14,25,16,20);

        // TreeMap é inerentemente ordenado 
        Map<Integer, Integer> mapIdades = new TreeMap<>();

        // Computa os valores do map, caso seja primeira ocorrência,
        // adiciona 1, senão vai incrementando.
        items.forEach(idade -> 
                mapIdades.compute(idade, (k, v) -> v == null ? 1 : ++v));

        // Percorre valores computados
        mapIdades.forEach((idade, quantidade) -> 
                System.out.println(idade + " : " + quantidade));

    }
}

By using a Map you can also access the values directly.

mapIdades.get(15); // 2
  

Url to test the code > > > here

    
06.09.2018 / 13:45