views:

72

answers:

1

I have a HashSet containing all groups I've retrieved from my database. I've been asked to filter this result by removing two specific groups. It seems trivial but I can't seem to come up with a solid solution for storing the specific groups I want to filter out.

My idea is to just create an array containing references to the two groups I need to filter out. I can then filter out my search query with whatever is in the array. My concern is that in the future they may ask to filter out more groups and maybe an array may not be a good idea.

//Creates the array containing groups to filter out

String[] hiddenGroups = {"group1","group2"};
//retrieves all groups
Set<String>allGroups = new HashSet<String>();
allGroups.addAll(authorityService.getAllAuthorities(AuthorityType.GROUP);
List<String>results = new ArrayList<String>();

//filters out specified groups 
for (String group : allGroups) {
  boolean isHidden = false;
  for (String hiddenGroup : hiddenGroups) {
    if (hiddenGroup.equalsIgnorecase(group)) {
      isHidden = true;
    }
  }
  if (!isHidden){
    results.add(group);
  }
}
+1  A: 

Looking up elements in a HashSet can be done in constant time. Because of that you can make your code more efficient by not looping over the elements in the HashSet and instead working from the full set and removing strings as you find that they are contained within the full set.

//Creates the array containing groups to filter out

String[] hiddenGroups = {"group1","group2"};

//retrieves all groups
Set<String>allGroups = new HashSet<String>();
allGroups.addAll(authorityService.getAllAuthorities(AuthorityType.GROUP);
Set<String>results = allGroups.clone();

//filters out specified groups 
for (String group : hiddenGroups) {
  if (allGroups.contains(group)) {
    results.remove(group);
  }
}

This will be fast even if there are a large number of groups since each is looked up in constant time.

Bialecki
HI Bialecki,Thanks for helping me optimize my code. I didnt know Hashset had those capabilities. One thing I want to add, however, is that using a for loop I came up with above gave a concurrent modifcation exception. To solve this, I just created an iterator and used it to iterate through the set.
Snowright