Reputation: 1417
I am fairly new to java and would like a container that I can use to hold strings that are not empty and have them sorted.
So far, I have mostly been using ArrayList, but this seems a bit limited for this case.
Thanks
Upvotes: 0
Views: 380
Reputation: 1417
Thanks for all the help. Here is what I eventually came up with, using TreeSet
and apache commons StringUtils
. My Input is a CSV String so, I didn't use the check on the input.
String csvString = "Cat,Dog, Ball, Hedge,, , Ball, Cat"
String[] array = StringUtils.split((String) csvString, ",");
for (int i = 0; i < array.length; i++)
{
array[i] = array[i].trim(); //Remove unwanted whitespace
}
set = new TreeSet<String>(Arrays.asList(array));
set.remove(""); //Remove the one empty string if it is there
set
now contains: Ball,Cat,Dog,Hedge
Upvotes: 0
Reputation: 894
A Set is what you want, as the items in it have to be unique. As the Strings should be sorted you'll need a TreeSet. As for the non blank Strings you have to override the insertion methods like this:
Set<String> sortedSetOfStrings = new TreeSet<String>() {
@Override
public boolean add(String s) {
if(s.isEmpty())
return false;
return super.add(s);
}
};
EDIT: Simplified thanks to Peter Rader's comment.
Upvotes: 2
Reputation: 85779
Use TreeSet
or TreeMap
, depending on your requirements. Both are collections that accept unique elements and keep them sorted.
Upvotes: 2