- There are standard ArrayList algorithms that utilize traversals to:
- determine a minimum or maximum value
- compute a sum or average
- determine if at least one element has a particular property
- determine if all elements have a particular property
- determine the number of elements having a particular property
- access all consecutive pairs of elements
- determine the presence or absence of duplicate elements
- Example 1: compute a sum or average
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
double sum = 0.0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
System.out.println("sum:" + sum);
sum = 0;
for (Integer x : list) {
sum += x;
}
System.out.println("sum:" + sum);
System.out.println(sum / list.size());
- Example 2: Find a minimum or maximum value
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(11);
list.add(41);
list.add(12);
list.add(30);
int max = list.get(0);
for (int i = 0; i < list.size(); i++) {
int x = list.get(i);
if (x > max) {
max = x;
}
}
System.out.println("max:" + max);
max = list.get(0);
for (int x : list) {
if (x > max) {
max = x;
}
}
System.out.println("max:" + max);
- Example 3: Check if a list is in increasing order
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(4);
list.add(3);
boolean isIncreasing = true;
int prev = list.get(0);
for (int i = 1; i < list.size(); i++) {
Integer current = list.get(i);
if (current < prev) {
isIncreasing = false;
}
prev = current;
}
System.out.println(isIncreasing);
- Example 4: count consecutive pairs
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(3);
list.add(3);
list.add(4);
list.add(3);
int count = 0;
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) == list.get(i + 1)) {
count++;
}
}
System.out.println(count);