Java:在排序列表中查找元素的最佳方法是什么?
我有一个
List<Cat>
按猫的生日排序的。 是否有一种有效的 Java Collections 方法来查找 1983 年 1 月 24 日出生的所有猫? 或者,一般来说什么是好的方法?
I have a
List<Cat>
sorted by the cats' birthdays. Is there an efficient Java Collections way of finding all the cats that were born on January 24th, 1983? Or, what is a good approach in general?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Collections.binarySearch()
< /a>.假设猫按生日排序,这将给出其中一只具有正确生日的猫的索引。 从那里,您可以前后迭代,直到找到具有不同生日的生日。
如果列表很长并且/或者没有多少猫有相同的生日,那么这应该是比直接迭代的重大胜利。
这是我正在考虑的代码。 请注意,我假设 随机访问 列表; 对于链表,你几乎陷入了迭代。 (感谢 Fred-o 在评论中指出这一点。)
Collections.binarySearch()
.Assuming the cats are sorted by birthday, this will give the index of one of the cats with the correct birthday. From there, you can iterate backwards and forwards until you hit one with a different birthday.
If the list is long and/or not many cats share a birthday, this should be a significant win over straight iteration.
Here's the sort of code I'm thinking of. Note that I'm assuming a random-access list; for a linked list, you're pretty much stuck with iteration. (Thanks to fred-o for pointing this out in the comments.)
二分查找是经典的方法。
澄清:我说你使用二分搜索。 没有具体的单一方法。 算法是:
Binary search is the classic way to go.
Clarification: I said you use binary search. Not a single method specifically. The algorithm is:
Google 集合可以通过使用谓词并创建过滤后的集合来执行您想要的操作谓词匹配日期。
Google Collections can do what you want by using a Predicate and creating a filtered collection where the predicate matches dates.
如果您需要真正快速的搜索,请使用以生日为键的 HashMap。 如果需要对键进行排序,请使用 TreeMap。
因为要允许多只猫有相同的生日,所以需要使用 Collection 作为 Hast/TreeMap 中的值,例如
If you need a really fast search use a HashMap with the birthday as a key. If you need to have the keys sorted use a TreeMap.
Because you want to allow multiple cats to have the same birthday, you need to use a Collection as a value in the Hast/TreeMap, e.g.
除非您以某种方式按日期索引集合,否则唯一的方法是迭代所有集合
Unless you somehow indexed the collection by date, the only way would be to iterate over all of them