• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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