There are several ways to do this. For example, without need to remove elements, you can use a sorted navigable collection such as a TreeSet
.
TreeSet<String> words = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
words.add("hello");
words.add("beta");
words.add("beat");
words.add("couch");
words.add("alpha");
words.add("Bad");
Now you can do
NavigableSet<String> bWords = words.subSet("b", true, "c", false);
System.out.println(bWords); // prints [Bad, beat, beta]
And you're given the subset of words that are >= b && < c
. You can then do
String removedWord = bWords.pollFirst(); // Bad
System.out.println(bWords); // prints [beat, beta]
// sub-sets affect their origin, they are "views on the original collection"
System.out.println(words); // prints [alpha, beat, beta, couch, hello]
And you've effectively removed a word with "b". A TreeSet
has the advantage that you can navigate and search your data in many ways.
Based on a char
the magic line of code to remove an element is
String removed = words.subSet(Character.toString(receivedLetter), true,
Character.toString((char) (receivedLetter + 1)), false)
.pollFirst();
The other alternative is a collection of collections. Like a SparseArray<List<String>>()
for example
SparseArray<List<String>> sparseArray = new SparseArray<List<String>>();
String str;
while ((str = stream.readLine()) != null) {
char c = str.charAt(0);
// get or create list stored at letter c
List<String> list = sparseArray.get(c);
if (list == null) {
list = new ArrayList<String>();
sparseArray.put(c, list);
}
// add word to list
list.add(str);
}
To remove, you get the list, if it's not null remove an element from it.
char receivedLetter;
List<String> words = sparseArray.get(receivedLetter);
if (words != null && !words.isEmpty())
words.remove(words.size() - 1);