I have a list of strings lst that is sorted lexicographically and I want to iterate over the list in a way that each iteration, I jump to a string that starts with the following letter of the first letter of the previous string.
For example, lst=["aba, "ads", "aerfa", "ba", "bdf", "cg", "cqr", "deg"]
The iteration will be: "aba" --> "ba" --> "cg" --> "deq"
If your list is small, the easiest solution might be to get the first char (
charAt(0)) and skip all subsequent elements until you find an element with a different first char, repeating that until the end of the list is reached.Otherwise, assuming your list is random-access (for example
ArrayList) you could probably do the following:With two variables, one for the current index (initially 0), and one for the potential next char.
chatAt(0)) increment it, cast it back tocharand store it as next char (for non-ASCII text you might need more elaborate logic)List.subListstarting behind the current index and ending at the end of the listCharacter.toString(char)) and search it in the sublist from the previous step usingCollections.binarySearch-(result + 1)(seebinarySearchdocumentation) add it to current index (since it is relative to the sublist) and repeat all steps(have not tested this implementation yet)
For a sorted String array you could probably get slightly better performance due to being able to use
Arrays.binarySearch.Maybe there are more efficient solutions to this though. Additionally, other data structures, such as
NavigableSetor a Trie might be useful as well.