I want to store all values of a certain variable in a dataset and the frequency for each of these values. To do so, I use an ArrayList<String>
to store the values and an ArrayList<Integer>
to store the frequencies (since I can't use int
). The number of different values is unknown, that's why I use ArrayList
and not Array
.
Example (simplified) dataset:
a,b,c,d,b,d,a,c,b
The ArrayList<String>
with values looks like: {a,b,c,d}
and the ArrayList<Integer>
with frequencies looks like: {2,3,2,2}
.
To fill these ArrayLists
I iterate over each record in the dataset, using the following code.
public void addObservation(String obs){
if(values.size() == 0){// first value
values.add(obs);
frequencies.add(new Integer(1));
return;//added
}else{
for(int i = 0; i<values.size();i++){
if(values.get(i).equals(obs)){
frequencies.set(i, new Integer((int)frequencies.get(i)+1));
return;//added
}
}
// only gets here if value of obs is not found
values.add(obs);
frequencies.add(new Integer(1));
}
}
However, since the datasets I will use this for can be very big, I want to optimize my code, and using frequencies.set(i, new Integer((int)frequencies.get(i)+1));
does not seem very efficient.
That brings me to my question; how can I optimize the updating of the Integer
values in the ArrayList
?
Use a HashMap<String,Integer>
Create the HashMap like so
HashMap<String,Integer> hm = new HashMap<String,Integer>();
Then your addObservation method will look like
public void addObservation(String obs) {
if( hm.contains(obs) )
hm.put( obs, hm.get(obs)+1 );
else
hm.put( obs, 1 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With