• Post Reply Bookmark Topic Watch Topic
  • New Topic

Standard idiom for getting subsets of a set ?  RSS feed

 
Steiner Egdal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a SortedSet<String> and would like to check a property for all of its subsets containing one string less than the set itself. Is there a standard way to do this ?

I don't like my idea below, which I haven't tried compiling yet. Since I am removing from the set while iterating, I have to use an Iterator rather than the simpler for-each loop.


 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think that's going to work. Removing the item via the iterator is fine - but then you're adding it back again within the loop, and that's also going to be a problem.

One approach that should work would be to take a copy of the set values first - e.g. by using toArray(). Then you can iterate through the copy, and within that loop you're free to add and remove items from the original set.

 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you can just create a new TreeSet to be the subset. Iterate through the original set normally; if the originalset contains an element for which hasInterestingProperty() is true, add it to the subset.

If you use Google Collections, you can do this:
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think that's quite the requirement - hasInterestingProperty refers to each possible subset (of size n - 1), not to individual elements.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, I read the question too quickly. Never mind.
 
Steiner Egdal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you are right about this not being legal. The code below



compiles, but results in



My problem is that I will be working with many set and they will be large, so I was hoping there was some trick to avoid creating the whole subsets,
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could create an array copy of the Set as Matthew suggested and then do your processing on that. Rather than removing an element from the array you could just ignore a specific element each time.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!