A simplistic version using ArrayLists could go like:
List<Integer> ints = new ArrayList<Integer>();
// Populate the list with some stuff
ints.add(5);
ints.add(20);
int sum = 0;
for (Integer anInt : ints) { // For each Integer in ints
sum += anInt; // Add it's value to the sum
}
double average = sum / ints.size();
Note the use of java's for-each or enhanced for loop for an ArrayList which greatly simplifies iteration. Also note that ArrayList cannot accept a primitive type for it's generic type, so we must take advantage of autoboxing and use the boxed type Integer
. Lastly, notice that the ArrayList object is being declared as a List
but instantiated as an ArrayList
.
If your values are strings that contain ints among other things. Then inside your loop you'll have to separate them. Regex would be a good tool for this. After a quick search, the accepted answer here looks like it solves it just fine number out of string in java
Edit:
This answer is too simple to as it doesn't care what the context of the data is. If you want to have each state have it's own set of stats. You could store them in a Map<String, Integer>
to pair the sum of each state with the name of that state.
Map<String, Integer> stateSums = new HashMap<String, Integer>();
stateSums.put("Oregon", 17);
stateSums.put("Utah", 9); //etc
Keep in mind that the put method will override an existing value if it's key already exists. So if you wanted to add a new value to the existing oregon key, you'd do something like: stateSums.put("Oregon", stateSums.get("Oregon") + 8);
Lets say you wanted to sort them but keep all their values completely separate! You can do that too:
Map<String, ArrayList<Integer>> stateValues = new HashMap<String, ArrayList<Integer>>
// Unless you can affirmatively determine whether or not this key
// already exists or not, you should check before each use to make sure
// you don't accidentally use a list that isn't created yet, or
// over-write one with data with a new empty one
if (!stateValues.containsKey("Oregon")) {
stateValues.put("Oregon", new ArrayList<>()); // It wasn't, create,
}
stateValues.get("Oregon").add(17);
stateValues.get("Oregon").add(8);
This solution would still require you to loop through your original data. Separate the state name and the number (Probably by regex), and then put each piece of data into it's proper place.
Hope this helps!
P.S. If you tell us what version of java you're running for this, we can optimize the results to utilize the latest available features. This will compile on at least 6, and maybe 5 and is consequently more verbose than it needs to be if you were running 7 or 8.