访问树集中的元素
我在这里尝试一些非常基本的java,但遇到了一些令人头疼的问题。本质上,我需要将文件中的某些元素读入某种类型的数组或列表中,对它们进行排序,消除重复项,然后返回前三个元素。 TreeSet 似乎非常适合,因为它可以进行排序并删除重复项。我的问题是我对如何仅返回前三个元素感到困惑。迭代器似乎贯穿整个集合。使用手动迭代器创建一个 while 循环来包含一个保存迭代器循环的 while 循环似乎令人困惑并且不太可能成功。这里的答案是我需要迭代树集并将每个元素放入数组列表中,以便我可以访问前三个元素吗?我的意思是,这似乎可行,但看起来非常复杂。尖端?
I am attempting some very basic java here and have reached a bit of a head scratcher. Essentially,I need to read some element from a file into some type of array or list, sort them, eliminate duplicates, and then return the first three elements. TreeSet seemed like the perfect fit in so much as it does the sort and kills the duplicates. My issue is that I am confounded as to how to return only the first three elements. The iterator seems to run all the way through the set. Creating a while loop with a manual iterator to contain a while loop that holds the iterator loops seems confusing and unlikely to be successful. Is the answer here that I need to iterate through the treeset and place each element into an arraylist so that I can then access the first three elements? I mean, it seems that this would work but it seems highly convoluted. Tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Guava 你可以这样做
Using Guava you could just do
嗯。显而易见的事情有什么问题吗?
或者
如果您更喜欢“脱糖”版本?
Hm. What's wrong with the obvious?
Or
if you prefer the "desugared" version?
字符串示例:
Example with Strings:
我会使用(希望您使用 Java 1.6):
编辑:使用我添加的
Math.min()
大小进行防弹I would use (expecting you use Java 1.6):
Edit: to be bulletproof with the size I added
Math.min()