user2971033
user2971033

Reputation:

Comparing objects: using enhanced for loop

I am iterating through an array of objects (different website types). But I want to be able to show which website has the highest amount of members. Initially my code shows the amount of members of each website, but my code isn't complete as im not sure how to compare the objects to see which has the highest amount of members. Current code:

public static void mostUsers(){

        for (Website w: websiteTypes){
            // check if the array index is not null
            if (w!=null){

                System.out.println(w.getType() + "has:" + w.getMembers());
                System.out.println(); // line break

                **//Code to compare amount of users on each site and display highest**
            } else {

                // no more records so quit loop
                break;
            }
        }
    }

Upvotes: 0

Views: 1821

Answers (2)

Alexis C.
Alexis C.

Reputation: 93862

You need to keep track of the maximum number of users while your iterating.

  1. Initialize a variable called maxWebsite to null before your loop
  2. Initialize an integer called max to Integer.MIN_VALUE before your loop
  3. While your iterating, test if w.getMaxUsers() is superior than the max value.
  4. If it is, update accordingly the maxWebsite and max variables

Note : remove the else statement in your loop, you have to iterate all the elements of your array.


If you're using Collections, that could be simple using Collections.max with a custom comparator :

List<Website> l = .......
l.removeAll(Collections.singleton(null)); //remove null elements from the list
Website maxWebsite = Collections.max(l, new Comparator<Website>(){
    @Override
    public int compare(Website arg0, Website arg1) {
        return Integer.compare(arg0.getMaxUsers(), arg1.getMaxUsers());
    }           
});

Upvotes: 1

William Morrison
William Morrison

Reputation: 11006

Use a Comparator, or have Website extend Comparable.

Then, sort your collection of Websites using sort. The websites with the most views will then be at the beginning of your collection.

Upvotes: 0

Related Questions