Howto remove elements from a List which are "lower" than specified element
I have a List<String>
which I sorted alphabetically using Collections.sort(...)
. Now I have a reference String
and I want to remove all Strings from the List
which are "lower" (in the alphabetical ordering) than my reference String. Is there any nice way to d开发者_运维百科o that or should I go through the List one by one and comparing each record to the reference value myself?
EDIT:
Since someone had asked for working solution here it is. originalList
is List<String>
... duplicities will be lost with this solution
String filterString = "...";
TreeSet<String> tSet = new TreeSet<String>(originalList);
List<String> filteredResources = new ArrayList<String>(tSet.tailSet());
If there are no duplicates, then you can do this:
- Create a TreeSet using the TreeSet constructor that takes a collection
- Now simply call TreeSet.tailSet(refString)
Once it's sorted it would be trivial using a ListIterator to iterate the list and perform the comparison. Once you're comparison misses, you know you can stop the iteration since your list was sorted.
Note though, that sorting is a relatively expensive operation, hence it would be more efficient to just iterate the list from start to end performing your comparison.
You could also employ an algorithm which checks the middle (list.size()/2
) element, then moves up or down again halfing the resultset, and so on until you've found the converging point.
E.g. looking for "f"
with a list {"a", "b", "c", "d", "e", "f", "g"}
would perform comparisons on middle element "d"
, then look at the middle "f"
element of the second half {"e", "f", "g"}
where a match is immediately found and the algorithm can stop.
Here is the best way I can think of.
- Sort the list
- Start going through the list one by one, starting from the lowest.
- Reach a point until the list element is higher than the one you have.
- Break out of the loop.
- Keep a note of this index and split the list using subList function by this index.
精彩评论