I've seen several other questions similar to this one but I haven't really been able to find anything that resolves my problem.
What would be the way to sort numberWords ArrayList based on ORDER array?
I'm not saying that numberWords must be ArrayList, it can be an array as well, but I thought it might fit better for getStoredWords() method as I should return List<String>.
Tried to compare numberWords to ORDER e.g. numberWords.get(first).equals(ORDER[first]), but it didn't work out the way it should.
public class WordStore {
List<String> numberWords = new ArrayList<>();
private static final String[] ORDER = {
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"
};
public void add(String numberAsWord) {
numberWords.add(numberAsWord);
}
public List<String> getStoredWords() {
}
}
Example tests:
public void insertedInArbitraryOrder() {
WordStore wordStore = new WordStore();
wordStore.add("three");
wordStore.add("one");
wordStore.add("two");
wordStore.add("ten");
wordStore.add("one");
wordStore.add("five");
wordStore.add("ten");
wordStore.add("nine");
wordStore.add("eight");
assertThat(wordStore.getStoredWords(),
contains("one", "one", "two", "three",
"five", "eight", "nine", "ten", "ten"));
}
public void insertedInReverseOrder() {
WordStore wordStore = new WordStore();
wordStore.add("three");
wordStore.add("two");
wordStore.add("one");
assertThat(wordStore.getStoredWords(),
contains("one", "two", "three"));
}
ORDERlike Lino already suggested. For larger lists you might also consider using aMap<String, Integer>which maps the words (keys) to some order (in your case those could be the actual integer values).binarySearch