2

I have a method that returns Sets of sets. Following is what I mean:

public static HashSet methodName(){
 HashSet c= new HashSet(); 

 c.add(x); //x is a HashSet of number
 c.add(y); //y is a Hashset of numbers

 return c;
}

After the method returns the collections, I enter it into an arraylist

ArrayList<HashSet> xxx= new ArrayList<Hashset>();
y=methodName();
xxx.add(y);

The method gets called couple of times and each time I enter sets of sets into the arraylist.

My question is. now I want to go through the arraylist and find the set that contains the smallest number of sets. How do I do that? Thanks so much in advance. Any help will be appreciated.

2 Answers 2

2

The size() method gives the cardinality of a HashSet. Simply write a Comparator<HashSet> and use Collections.max().

Sign up to request clarification or add additional context in comments.

Comments

0

A simple way you to go through an array is through an Iterator. These are utilized in a foreach loop, which can be used when you know the type of elements used in an array (via generics). You can use that in your outer HashSet- containing ArrayList:

for (HashSet set : xxx) {
    // you need to iterate over the elements in your HashSet here and determine which internal Set has the most elements
    for ( Iterator iter = set.iterator(); iter.hasNext();) {
        HashSet innerSet = (HashSet) iter.next();
        // do the size test
     }

}

2 Comments

can you please show me the whole code. How would you compare the size
HashSet smallest = null; for (HashSet currentSet : xxx) {if (smallest == null || smallest.size() > currentSet.size()) smallest = currentSet;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.