ArrayList Loop Patterns


Find Minimum (or Maximum)

/** Ratings are between 1 and 5.
 *  A "rating" of 0 means there were no reviews.
 */
public int lowestRating()
{
   // An empty list is a special case
   if ( reviewList.isEmpty() )
      return 0;

   // Let's assume the first one is the lowest...
   int lowRating = reviewList.get(0).getRating();

   // And then see if there's one lower
   for ( MovieReview review : reviewList )
   {
      if ( review.getRating() < lowRating )
          lowRating = review.getRating();
   }

   // By the end, we've found the minimum
   return lowRating;
}
/** Ratings are between 1 and 5.
 *  A "rating" of 0 means there were no reviews.
 */
public int lowestRating()
{
   // An empty list is a special case
   if ( reviewList.size() == 0 )
      return 0;

   // Let's assume the first one is the lowest...
   int lowRating = reviewList.get(0).getRating();

   // And then see if there's one lower
   for ( int i = 1; i < reviewList.size(); i++ )
   {
      MovieReview review = reviewList.get(i);
      if ( review.getRating() < lowRating )
          lowRating = review.getRating();
   }

   // By the end, we've found the minimum
   return lowRating;
}
/** Ratings are between 1 and 5.
 *  A "rating" of 0 means there were no reviews.
 */
public int highestRating()
{
   int highRating = 0;   // Value if no reviews.

   // If there are any ratings, they will
   //    all be higher than 0.

   // Now see if there's one higher
   for ( MovieReview review : reviewList )
   {
      // int rating = review.getRating();
      if ( review.getRating() > highRating )
          highRating = review.getRating();
   }

   // By the end, we've found the maximum
   return highRating;

}
/** Ratings are between 1 and 5.
 *  A "rating" of 0 means there were no reviews.
 */
public int highestRating()
{
   int highRating = 0;   // Value if no reviews.

   // If there are any ratings, they will
   //    all be higher than 0.

   // Now see if there's one higher
   for ( int i = 0; i < reviewList.size(); i++ )
   {
      MovieReview review = reviewList.get(i);
      if ( review.getRating() > highRating )
          highRating = review.getRating();
   }

   // By the end, we've found the maximum
   return highRating;

}

Alyce Brady, Kalamazoo College