I have written this method which calculates the range (max - min) of an ArrayList
. I have two for
loops each for a different ArrayList
. The for
loops do exactly the same thing except they each use a different list, so I was wondering if there was a way to just use one for
loop (or any other way) that does the work but iterates through both ArrayList
s so that I don't have nearly identical for
loops.
public static void calcRange(ArrayList <Integer> list1, ArrayList<Integer> list2){
int max = list1.get(0);
int min = list1.get(0);
int max2 = list2.get(0);
int min2 = list2.get(0);
for (int i : list1){
if ( i > max){
max = i;
} else if (i < min){
min = i;
}
}
for (int i : list2){
if ( i > max2){
max2 = i;
} else if (i < min2){
min2 = i;
}
}
System.out.println("List 1 Range: "+(max - min)+"\tList 2 Range: "+(max2 - min2));
}