Java:如何在指定列表的第一个元素时从设置转换为列表

发布于 2025-02-12 23:18:30 字数 538 浏览 0 评论 0 原文

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,然后将其添加到列表中,然后添加其余的元素。我只是想知道最干净的方法是什么。

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);
}

Is there a way to convert from a Set to a List and guaranteeing element1 is the first element in the List? I do not care about the ordering for the rest of the elements in the List only the very first element. I could remove element1 from the Set then add it to the List then add the rest of the element. I'm just wondering what is the cleanest way to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

今天小雨转甜 2025-02-19 23:18:30

se t转换为 list 和保证 element1 list> list 中的第一个元素?

为此,您需要使用 linkedhashset 能够维护元素的顺序而不是 Hashset

Set<Foo> fooSet = new LinkedHashSet<>();

fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);

List<Foo> fooList = new LinkedList<>(fooSet);

而且,由于您添加了标签 java-stream 似乎使用您正在考虑基于流的解决方案,我要指出, 不需要创建 stream 并使用 collector 只是为了将相同的数据丢弃而没有任何更改。

当然,没有人能够禁止您正确地这样:

List<Foo> fooList = fooSet.stream().collect(Collectors.toList());

但这将是滥用流

convert from a Set to a List and guaranteeing element1 is the first element in the List?

For that, you need to use a LinkedHashSet which is capable of maintaining the order of elements instead of HashSet.

Set<Foo> fooSet = new LinkedHashSet<>();

fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);

List<Foo> fooList = new LinkedList<>(fooSet);

And since you've added the tag 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:

List<Foo> fooList = fooSet.stream().collect(Collectors.toList());

But it would be a misuse of streams.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文