Java:如何在指定列表的第一个元素时从设置转换为列表
static void main(String[] args) {
List<Foo> fooList = new LinkedList<>();
Set<Foo> fooSet = new HashSet<>();
Foo element1 = new Foo("Element1");
Foo element2 = new Foo("Element2");
Foo element3 = new Foo("Element3");
fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);
CollectionUtils.addAll(fooList, fooSet);
}
有没有一种方法可以从集合转换为列表,并且保证元素1是列表中的第一个元素?我不在乎列表中其余元素的订购仅是第一个元素。我可以从集合中删除元素1,然后将其添加到列表中,然后添加其余的元素。我只是想知道最干净的方法是什么。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,您需要使用
linkedhashset
能够维护元素的顺序而不是Hashset
。而且,由于您添加了标签 java-stream 似乎使用您正在考虑基于流的解决方案,我要指出, 不需要创建 stream 并使用 collector 只是为了将相同的数据丢弃而没有任何更改。
当然,没有人能够禁止您正确地这样:
但这将是滥用流。
For that, you need to use a
LinkedHashSet
which is capable of maintaining the order of elements instead ofHashSet
.And since you've added the tag java-stream it seems like use you were thinking of stream-based solution, I would point out that there's no need to create a stream and utilize a collector just in order to dump the same data without any changes into a list.
Sure, no one has a power to prohibit you to right such line:
But it would be a misuse of streams.