Reputation:
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
Reputation: 93862
You need to keep track of the maximum number of users while your iterating.
maxWebsite
to null
before your loopmax
to Integer.MIN_VALUE
before your loopw.getMaxUsers()
is superior than the max
value.maxWebsite
and max
variablesNote : remove the else statement in your loop, you have to iterate all the elements of your array.
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
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