如何从列表中删除“较低”的元素比指定元素
我有一个 List
,我使用 Collections.sort(...)
按字母顺序排序。现在我有一个参考字符串,我想从列表中删除所有比我的参考字符串“低”(按字母顺序排列)的字符串。有没有什么好的方法可以做到这一点,或者我应该逐一浏览列表并自己将每条记录与参考值进行比较?
编辑: 因为有人在这里要求工作解决方案,所以就是这样。 originalList
是 List
...此解决方案将丢失口是心非
String filterString = "...";
TreeSet<String> tSet = new TreeSet<String>(originalList);
List<String> filteredResources = new ArrayList<String>(tSet.tailSet());
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 do 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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果没有重复项,则可以执行以下操作:
If there are no duplicates, then you can do this:
一旦排序,使用 ListIterator 迭代列表并执行比较。一旦比较失败,您就知道可以停止迭代,因为您的列表已排序。
但请注意,排序是一项相对昂贵的操作,因此从头到尾迭代列表来执行比较会更有效。
您还可以采用一种算法来检查中间 (
list.size()/2
) 元素,然后再次向上或向下移动,将结果集减半,依此类推,直到找到收敛点。例如,使用列表查找
"f"
{"a", "b", "c", "d", "e", "f", "g"} 将对中间元素
"d"
进行比较,然后查看后半部分{"e", "f" 的中间
其中立即找到匹配并且算法可以停止。"f"
元素, "g"}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.