Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 187
  • Last Modified:

Calucuting a max on an arbitrary property within a collection of objects?

I have a collection of Items.

say for example:  Collection items = new ArrayList();

Items class has a property called maxOccurrenceCount

I want to calcutate that which item has the maxOccurrenceCount out of the entire collection.


Thanx in advance.
0
slickdeals
Asked:
slickdeals
  • 2
2 Solutions
 
CEHJCommented:
Sort it using a Comparator on maxOccurrenceCount or, if it implements Comparable, you can do

Collections.max(itemsCollections);
0
 
slickdealsAuthor Commented:
No my object does not have a comparator.

This is how the object looks like :

class Item{
private Integer maxOccurrenceCount;
// gets and sets
}

How can i add a comparator. thanx for the input.
0
 
CEHJCommented:
Collections.max(itemsCollection, new Comparator() {
      public int compare(Object o1, Object o2) {
            return ((Item)o1).getMaxOccurrenceCount().compareTo((Item)o2).getMaxOccurrenceCount());
      }
});
0
 
mrigankCommented:
Iterator iterator = items.iterator();
Item maxItem = (Item)iterator.next();

while(iterator.hasNext()){
   Item nextItem = (Item)it.next();
   if(nextItem.getMaxOccurencCount() > maxItem.getMaxOccurenceItem())
       maxItem = nextItem;
}

return maxItem;
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now